spring bean 加载多个配置文件 <import>

it2024-08-03  49

第一步: 新建工程 SecondSpring

工程目录结构如下:

 

第二步:导入响应的jar包

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.1.RELEASE</version> <type>jar</type> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.1.RELEASE</version> <type>jar</type> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.3.1.RELEASE</version> <type>jar</type> </dependency>

第三步: 新增类

Frult.java

package com.xuzhiwen.spring1; public class Frult { private String name; private int age; public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Frult [name=" + name + ", age=" + age + "]"; } }

第四步:新增配置文件

common.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <import resource="xmlfolder/app1.xml" /> </beans>

第五步: 在 xmlfolder文件夹下新增app1.xml文件

app1.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="frult" class="com.xuzhiwen.spring1.Frult" p:name="apple" p:age="30" /> </beans>

第六步:编写测试类

Test.java

package com.xuzhiwen.spring1; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { ApplicationContext app = new ClassPathXmlApplicationContext("common.xml"); Frult f = (Frult) app.getBean("frult"); System.out.println(f); } }

第七步:运行结果如下

 

注意在Spring3,所述替代解决方案是使用 JavaConfig @Import.

 

转载于:https://www.cnblogs.com/beibidewomen/p/7388259.html

最新回复(0)