03_Spring Bean 工厂方式实例化

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
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EngineerForSoul

你的鼓励是我孜孜不倦的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值