Spring创建对象的三种方式:
方式一:通过构造器<bean class="" id=""></bean>
方式二:通过工厂方法创建<bean class="" factory-method="" id=""></bean>
方式三:通过实例工厂方法创建(调用某对象的非静态方法来创建对象)<bean factory-bean="" factory-method="" id=""></bean>实例工厂方法创建对象必须是容器中已经申明的对象。
Bean的作用域-->singleton(每个类型的bean在容器中默认是单例) prototype
<bean id="" class="" scope="prototype"></bean>
Bean的生命周期
<bean id="" class="" init-method=""></bean>容器创建bean之后自动调用
<bean id="" class="" destroy-method=""></bean>容器关闭AbstractApplicationContext类中的 close()时自动调用
lazy-init:懒加载,只对单例的bean有效。
<bean id="" class="" init-methd="" destroy-method="" lazy-init=""></bean>
IOC(Inversion of controller,控制反转)
创建和管理对象交给spring容器,而不是开发者来管理。
spring 通过DI(Dependency Injection,依赖注入)的方式实现。
DI有两种方式:
1.Setter注入:通过bean的set方法,给它注入参数。
<bean id="" class="">
<property name="" value=""/>
</bean>
2.构造器注入(对于bean的成员变量一定要传入时使用此方法)
<bean>
<constructor-arg index="0" value="" />
<constructor-arg name="" value="" />两种方式都可以
</bean>
自动装配:spring容器可以自动装配(autowire),一共有5中类型
no(禁用,默认值)
byName(根据属性名自动装配)
byType(根据bean类型装配,属性类型一致,通过setter注入)
constructor(和byType类似,通过构造器)
autodetect
<bean id="" class="" autowire="byType"></bean>
注入参数:
List集合注入:
<bean id="" class="">
<property>
<list>
<value>
<value>
<value>
</list>
</property>
</bean>
Set集合注入:
map集合注入
<bean id="" class="">
<property>
<map>
<entry key="" value="">
<entry key="" value="">
</map>
</property>
</bean>
基于注解的方式配置
<context:component-scan base-package="">
@Component
@Repository
@Resource
@Controller
@Scope("singleton")
@Lazy(true)
@PostConstruct
@PreDestroy
@Autowired/@Qualifier
通过set方式
方式一//如果没有使用@Qualifier指定bean的id,默认使用byType的方式
@Autowired
public void setxxx( @Qualifier("person")Person person){}
方式二
@Autowired
@Qualifier("person")
private Person person;
通过构造器
@Autowired
public Test(@Qualifier("person")Person person){}
读取指定路径下的properties文件内容
<util:properties id="config" location="classpath:config.properties">
@Value("#{config.pagesize}")
private String pageSize;