注解@Resource与@Autowired与@Component的使⽤
在java代码中使⽤@Autowired或@Resource注解⽅式进⾏装配,这两个注解的区别是:@Autowired 默认按类型装配,@Resource默认按名称装配,当不到与名称匹配的bean才会按类型装配。
@Autowired private PersonDao personDao;//⽤于字段上
resource和autowired注解的区别@Autowired public void setOrderDao(OrderDao orderDao) {//⽤于属性的setter⽅法上
S pring注解@Component和@resource的使⽤
@Component(“”)和@resource(name=””)的使⽤:
spring的配置⽂件配置:
配置解析:
使⽤ClassPathXmlApplicationContext(“l”)初始化l的时候,或者说初始化spring配置⽂件的时候,会⾃动扫描st下的所有包,若发现有@component,则将该类初始化为⼀个对象,对
象的key为@component(“name”)中指明的name,若不指明,则默认为类的名字⾸字母⼩写;当调⽤Bean(“userService”),时,则查看容器是否有⼀个名字为userService;如有则在初始化这个类得过程中,如果发现@Resource(name=”u”);则查看容器是否有名字叫u的bean,若有则将u注⼊到⽅法参数中,⽽后参数就会传⼈⽅法内,当然也就注⼊了成员变量⾥:
UserService.java⽂件中使⽤:
@Component(“userService”)
public class UserService {
private UserDAO userDAO = new UserDAOImpl(); private UserLogDAO userLogDAO;
public UserDAO getUserDAO() {
return userDAO;
}
public UserLogDAO getUserLogDAO() {
return userLogDAO;
}
@Resource(name="ulog")
public void setUserLogDAO(UserLogDAO userLogDAO) { this.userLogDAO = userLogDAO;
}
@Resource(name="u")
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
UserDAOImpl.java中使⽤:
@Component("u")
public class UserDAOImpl implements UserDAO {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
@Resource
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public void save(User u) {
Session s=sessionFactory.openSession();//.getCurrentSession();
//s.beginTransaction();
s.save(u);
System.out.println("a user save,XXXX!");
}
}
使⽤上述的@Component和@resource注解,相当于spring使⽤了如下的配置:这样就可以省去之前在bean中所写的:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论