Spring 工厂方式实例化Bean
静态工厂方式实例化
UserFactory类
public class UserFactory {
public static User newInstance(String name) {
return new User(name);
}
}
user类
public class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
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="user" class="cn.lingyiwin.factory.UserFactory" factory-method="newInstance">
<constructor-arg index="0" value="静态工程创建bean"/>
</bean>
</beans>
执行结果:
public class TestUser {
public static void main(String[] args) {
ApplicationContext act =new ClassPathXmlApplicationContext("config/spring.xml");
User user = (User)act.getBean("user");
System.out.println(user);
System.out.println(user.getName());
}
}
cn.lingyiwin.bean.User@56ac3a89
静态工程创建bean
实例工厂方式bean实例化
UserDynamicFactory 类
public class UserDynamicFactory {
public static User newInstance(String name) {
return new User(name);
}
}
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 ="userFactory" class="cn.lingyiwin.factory.UserDynamicFactory"/>
<bean id="user" factory-bean="userFactory" factory-method="newInstance">
<constructor-arg index="0" value="动态工程创建bean"/>
</bean>
</beans>
执行结果报错了:
Error creating bean with name 'user' defined in class path resource [config/spring.xml]:
No matching factory method found: factory bean 'userFactory'; factory method
'newInstance(String)'. Check that a method with the specified name and
arguments exists and that it is non-static.
工厂中方法newInstance 不能是静态的
。
修改UserDynamicFactory 类
public class UserDynamicFactory {
public User newInstance(String name) {
return new User(name);
}
}
执行结果:
cn.lingyiwin.bean.User@56ac3a89
动态工程创建bean