您的位置:首页 > 编程语言 > Java开发

spring bean装配 注册动态工厂和静态工厂

2017-05-15 14:28 453 查看
默认的装配方式:代码通过getbean()方式从容器获取指定的bean实例容器首先会调用bean的无参构造器。创建控制的实例对象注册动态的工厂applicationcontext.xml
<?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="factory" class="com.bjpowernode.ba02.ServiceFactory"/>

<!-- 注册Service:动态工厂Bean -->
<bean id="myService" factory-bean="factory" factory-method="getSomeService"/>

</beans>
实现接口和实体类factory类
public class ServiceFactory {
public ISomeService getSomeService() {
return new SomeServiceImpl();
}
public class SomeServiceImpl implements ISomeService {
private int a;

public SomeServiceImpl() {
System.out.println("执行无参构造器");
}

/*
public SomeServiceImpl(int a) {
this.a = a;
}
*/

@Override
public void doSome() {
System.out.println("执行doSome()方法");
}

}
接口
public interface ISomeService {
void doSome();
}
测试类
public class MyTest {

@Test
public void test01() {
ISomeService service = new ServiceFactory().getSomeService();
service.doSome();
}

@Test
public void test02() {
// 创建容器对象,加载Spring配置文件
String resource = "com/bjpowernode/ba02/applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(resource);
ISomeService service = (ISomeService) ac.getBean("myService");
service.doSome();
}

}
静态工厂:applicationcontext.xml<?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"><!-- 注册Service:静态工厂Bean --><bean id="myService" class="com.bjpowernode.ba03.ServiceFactory" factory-method="getSomeService"/></beans>接口:
public interface ISomeService {
void doSome();
}
实现类:public class SomeServiceImpl implements ISomeService { private int a; public SomeServiceImpl() { System.out.println("执行无参构造器"); } /* public SomeServiceImpl(int a) { this.a = a; } */ @Override public void doSome() { System.out.println("执行doSome()方法"); } }工厂类public class ServiceFactory {public static ISomeService getSomeService() {return new SomeServiceImpl();}}测试类public class MyTest {@Testpublic void test01() {// 创建容器对象,加载Spring配置文件String resource = "com/bjpowernode/ba03/applicationContext.xml";ApplicationContext ac = new ClassPathXmlApplicationContext(resource);ISomeService service = (ISomeService) ac.getBean("myService");service.doSome();}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: