基于XML配置bean的基本方式
代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
其中
id=””表示你对bean的命名;
class=””表示的是bean类的路径;
配置中是可以配置多个bean的
示例:
Bean
//Hello.java
package com.wenj.services;
public interface Hello {
public void sayHello();
}
//HelloImpl.java
package com.wenj.servicesimpl;
import com.wenj.services.Hello;
public class HelloImpl implements Hello {
@Override
public void sayHello() {
System.out.println("Hello World");
}
}
配置bean
代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
<bean id="hello" class="com.wenj.servicesimpl.HelloImpl"></bean>
</beans>
Test
新建一个jUnit test case
在里面添加如下代码
@Test
public void test(){
ApplicationContext cxt = new ClassPathXmlApplicationContext("com/wenj/resources/beans.xml");
Hello h = (Hello) cxt.getBean("helloImpl");
h.sayHello();
}
实例化一个Spring Ioc容器
注意到以上的测试代码
ApplicationContext cxt = new ClassPathXmlApplicationContext("com/wenj/resources/beans.xml");
此代码片段式就是用于实例化Spring IoC容器的, 同时容器是可以加载多个xml文件的,如:
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});
其中就可以加载services.xml和daos.xml
使用容器获取bean对象
Hello h = (Hello) cxt.getBean("helloImpl");
这里通过id来获取容器中的bean对象
至此运行,可以在控制台输出
Hello World!