默认的装配方式:
代码通过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 {
@Test
public void test01() {
// 创建容器对象,加载Spring配置文件
String resource = "com/bjpowernode/ba03/applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(resource);
ISomeService service = (ISomeService) ac.getBean("myService");
service.doSome();
}
}