Spring如何初始化Bean:Bean初始化的方式
1、通过bean全类名,通过反射的方式在IOC容器中创建Bean,所以Bean中必须有无参数的构造器。通过ID从同柙丕牌容器中获取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="department" class = "com.gwolf.springmvc.domain.Department"> <property name="departmentName" value="技术部"></property> </bean> </beans>
2、属性注入即通过setter方法注入Bean的属性值或者依赖的对象。
3、构造方法注入:通过构造方法注入Bean的属性值或依赖的对象,它保证了Bean实例在实例化后就可以使用。
4、我们在需要初始化的方法中提供一个属性的构造器:
5、在application.xml中使用构造方法初始化:<?xml version="1.0" enco颊俄岿髭ding="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="department" class = "com.gwolf.springmvc.domain.Department"> <constructor-arg value="10"></constructor-arg> <constructor-arg value="测试部门"></constructor-arg> </bean> </beans>
6、在main方法中打印属性是否赋值成功了。