Web.xml的配置、PersonDao类、PersonDao类与1中相同。
自动扫描机制就是,它可以在类路径下寻找标注了@Component、@Service、@Controller、@Repository注解的类,并把这些类纳入Spring容器中管理。
1)PersonDaoBean 类:
@Repository
public class PersonDaoBean implements PersonDao {
public void add() {
System.out.println("执行personDao中的add()方法!");
}
}
2)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">
<!-- 添加的自动扫描组件,base-package为要扫描的包(包括子包)-->
<context:component-scan base-package="springDaoBean" />
</beans>
3)PersonServiceBean 类:
//@Service
// 直接访问PersonServiceBean类
@Service("personService")
// 先访问personService类然后跳转到PersonServiceBean类
@Scope("prototype")
// 每次用PersonServiceBean类都会生成一个新的对象
public class PersonServiceBean implements PersonService {
private PersonDao personDao;
@PostConstruct
// 当实例化PersonServiceBean类时会调init方法
public void init() {
System.out.println("初始化");
}
@PreDestroy
// 当正常关闭资源时回调用destroy方法
public void destroy() {
System.out.println("关闭资源");
}
public void save() {
personDao.add();
}
}
4)springTest 类:
public class springTest {
@Test
public void instanceSpring() {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("springXml/beans.xml");
// 使用@Service直接放问PersonServiceBean
// PersonService personServiceBean = (PersonService) ctx.getBean("personService");
// System.out.println(personServiceBean);
// 使用@Service("personService")间接访问PersonServiceBean
// PersonService personService = (PersonService)ctx.getBean("personService");
// System.out.println(personService);
// 在PersonServiceBean类中可以添加@scope("prototype")是每 次实例化都生成一个新的对象
// PersonService personService1 = (PersonService)ctx.getBean("personService");
// PersonService personService2 = (PersonService)ctx.getBean("personService");
// System.out.println(personService1 == personService2);
// 在personServiceBean中添加@PostConstruct, 实例化类对象时会调用init()方法
PersonService personServiceBean = (PersonService)ctx.getBean("personService");
System.out.println(personServiceBean);
// 在personServiceBean中添加@PreDestroy,在正常关闭资源时会调用destroy()方法
ctx.close();
}
}
@Service用于标注业务层组件,@Controller用于标注控制层组件(如struts中的action)、@Repository用于标注数据访问组件(DAO组件)、@Component扫描那些不好归类的组件。