三、Bean的懒加载和生命周期

最后更新于:2022-04-01 11:38:10

懒加载 ~~~ <?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-2.5.xsd" default-lazy-init="true"> <bean id="userDao" class="com.spring.dao.UserDaoImpl"></bean> <bean id="userService" class="com.spring.service.UserServiceImpl" scope="prototype"> <property name="userDao" ref="userDao"></property> </bean> <!-- 这里的懒加载。也就是说在我们程序中真正get指定bean的 时候才会实例化这个bean而且也有全局的声明在xml文件上,否则在容器初始化的时候就开始声明初始化实例了。 --> <bean id="userAction" class="com.spring.action.UserAction" autowire="byName" lazy-init="true"> </bean> </beans> ~~~ 生命周期: bean的声明周期是要在配置文件中指定并且要在bean中编写的。下面看两个文件: 1、 xml配置文件: ~~~ <bean id="userService" class="com.spring.service.UserServiceImpl" init-method="init" destroy-method="destory"> <property name="userDao" ref="userDao"></property> </bean> ~~~ Java文件: ~~~ public class UserServiceImpl implements UserService{ private UserDao userDao; public void init(){ System.out.println("init"); } public void destory(){ System.out.println("destory"); } ~~~
';