首页 > 代码库 > Spring Annotation(@resource、@component)

Spring Annotation(@resource、@component)

技术分享
 1 package com.bxw.dao.impl;
 2 
 3 import org.springframework.stereotype.Component;
 4 
 5 import com.bxw.dao.UserDao;
 6 import com.bxw.po.User;
 7 
 8 @Component("userDao")
 9 public class UserDaoImpl implements UserDao {
10     public void save(User u){
11         System.out.println("user saved");
12     }
13 }
UserDaoImpl.java

@Component("userDao"):括号内不指定属性时默认是value="http://www.mamicode.com/userDao"。

@Service用于标注业务层组件,

@Controller用于标注控制层组件(如struts中的action),

@Repository用于标注数据访问组件,即DAO组件,

@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。

 

技术分享
 1 package com.bxw.service;
 2 
 3 import javax.annotation.Resource;
 4 
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.beans.factory.annotation.Qualifier;
 7 import org.springframework.stereotype.Service;
 8 
 9 import com.bxw.dao.UserDao;
10 import com.bxw.dao.impl.UserDaoImpl;
11 import com.bxw.po.User;
12 
13 @Service
14 public class UserService {
15     private UserDao userDao = new UserDaoImpl();
16     
17     public void init() {
18         System.out.println("init...");
19     }
20     
21     public UserDao getUserDao() {
22         return userDao;
23     }
24 
25     @Resource(name="userDao")
26     public void setUserDao(UserDao userDao) {
27         this.userDao = userDao;
28     }
29     
30     public void add(User u){
31         this.userDao.save(u);
32     }
33     
34     public void destroy() {
35         System.out.println("destroy...");
36     }
37     
38 }
UserService.java

@Resource(name="userDao"),spring会从包里扫描,如果扫描到名为userDao的组件,会注入进去。

 

技术分享
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans
 3     xmlns="http://www.springframework.org/schema/beans"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 6     xmlns:p="http://www.springframework.org/schema/p"
 7     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 8     
 9     <context:component-scan base-package="com.bxw"></context:component-scan>
10 
11 </beans>
applicationContext.xml

<context:component-scan base-package="com.bxw"></context:component-scan>:配置spring容器扫描component,在com.bxw的包(子包)内。

 

Spring Annotation(@resource、@component)