<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="cn.itcast"/>
public class PersonServiceBean implements PersonService {
private PersonDao personDao;
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
PersonService personService = (PersonService)ctx.getBean("personServiceBean");/personService
System.out.println(personService);
ctx.close();
--------------------------------------------------------------------------------------------------------------------------------------
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="cn.itcast"/>
</beans>
@Service /@Service("personService") // Scope("prototype")public class PersonServiceBean implements PersonService {
private PersonDao personDao;
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
@PostConstruct 参见: --------Spring(二)bean实例化-----
public void init(){
System.out.println("初始化");
}
@PreDestroy
public void destory(){
System.out.println("开闭资源");
}
}
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");PersonService personService = (PersonService)ctx.getBean("personServiceBean");/personService
System.out.println(personService);
ctx.close();
--------------------------------------------------------------------------------------------------------------------------------------
本文介绍了一个使用Spring框架管理Bean生命周期的例子。通过定义PersonServiceBean类并实现PersonService接口,演示了如何利用@PostConstruct和@PreDestroy注解来指定Bean的初始化和销毁方法。此外,还展示了如何配置Spring来扫描特定包下的组件。
1297

被折叠的 条评论
为什么被折叠?



