1、组件自动扫描机制
Spring会在类路径下寻找标注@Component、@Service、@Controller、@Repository注解的类,并把这些类纳入Spring容器管理。其中,@Component,泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。@Service,业务层组件。@Controller,控制层组件。@Repository,数据访问层组件,即DAO组件。使用组件自动扫描机制,需要在配置文件中添加配置信息,如,<context:component-scan base-package="包"/>。该配置项包含了配置注册对注解进行解析处理的处理器,因此当使用<context:component-scan base-package="包"/>配置项时,可省略<context:annotation-config/>配置项。
2、实例
(1)PersonDao.java
public interface PersonDao { public void add(); }
(2)PersonDaoBean.java
@Repository public class PersonDaoBean implements PersonDao { public void add() { System.out.println("PersonDaoBean add"); } }
(3)PersonService.java
public interface PersonService { public void save(); }
(4)PersonServiceBean.java
/** * @Scope("prototype")指定创建bean的模式 */ @Service("personService") @Scope("prototype") public class PersonServiceBean implements PersonService { private PersonDao personDao; /** * @PostConstruct指定初始化bean之后调用的方法 */ @PostConstruct public void init() { System.out.println("init"); } /** * @PreDestroy指定销毁bean之前调用的方法 */ @PreDestroy public void destory() { System.out.println("destory"); } public PersonServiceBean() {} public PersonServiceBean(PersonDao personDao) { this.personDao = personDao; } public void save() { personDao.add(); } }
(5)beans.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" 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="com.spring"/> </beans>
(6)Test.java
public class Test { @org.junit.Test public void test() { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); PersonService personService1 = (PersonService)ctx.getBean("personService"); PersonService personService2 = (PersonService)ctx.getBean("personService"); System.out.println(personService1 == personService2); PersonDao personDao = (PersonDao)ctx.getBean("personDaoBean"); personDao.add(); } }
3、结果
test()运行结果:
init init false PersonDaoBean add
