@Component(“”)和@resource(name=””)的使用:
spring的配置文件配置:
xml version="1.0" encoding="UTF-8"?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
配置
使用ClassPathXmlApplicationContext("bean.xml")初始化bean.xml的时候,或者说初始化spring配置文件的时候,会自动扫描com.test下的所有包,若发现有@component,则将该类初始化为一个对象,对象的key为@component("name")中指明的name,若不指明,则默认为类的名字首字母小写;当调用ctx.getBean("userService"),时,则查看容器是否有一个名字为userService;如有则在初始化这个类得过程中,如果发现@Resource(name=”u”);则查看容器是否有名字叫u的bean,若有则将u注入到方法参数中,而后参数就会传人方法内,当然也就注入了成员变量里:
UserService.java文件中使用:
@Component("userService")
publicclassUserService{
privateUserDAO userDAO =newUserDAOImpl();
privateUserLogDAO userLogDAO;
publicUserDAO getUserDAO(){
return userDAO;
}
publicUserLogDAO getUserLogDAO(){
return userLogDAO;
}
@Resource(name="ulog")
publicvoid setUserLogDAO(UserLogDAO userLogDAO){
this.userLogDAO = userLogDAO;
}
@Resource(name="u")
publicvoid setUserDAO(UserDAO userDAO){
this.userDAO = userDAO;
}
UserDAOImpl.java中使用:
@Component("u")
publicclassUserDAOImplimplementsUserDAO{
privateSessionFactory sessionFactory;
publicSessionFactory getSessionFactory(){
return sessionFactory;
}
@Resource
publicvoid setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
@Override
publicvoid save(User u){
Session s=sessionFactory.openSession();//.getCurrentSession();
//s.beginTransaction();
s.save(u);
System.out.println("a user save,XXXX!");
}
}
使用上述的@Component和@resource注解,相当于spring使用了如下的配置:
这样就可以省去之前在bean中所写的: