@Component 注解

@Component
  a) 初始化的名字默认为类名首字母小写:UserService 在容器中默认为 userService
  b) 可以指定初始化 bean 的名字: 1 @Component(value="userService") 

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:annotation-config />
  
  <context:component-scan base-package="com.bjsxt" /><!-- 指定包 -->
  
</beans>

bean 配置:

  UserDAOImpl

 1 package com.bjsxt.dao.impl;
 2 
 3 import org.springframework.stereotype.Component;
 4 
 5 import com.bjsxt.dao.UserDAO;
 6 import com.bjsxt.model.User;
 7 
 8 @Component    //默认名字:userDAOImpl
 9 public class UserDAOImpl implements UserDAO{
10 
11     public void save(User u) {
12         System.out.println("a user saved!");
13     }
14 
15 }
View Code

  UserService

 1 package com.bjsxt.service;
 2 
 3 import javax.annotation.Resource;
 4 
 5 import org.springframework.stereotype.Component;
 6 
 7 import com.bjsxt.dao.UserDAO;
 8 import com.bjsxt.model.User;
 9 
10 @Component(value="userService")
11 public class UserService {
12     
13     private UserDAO userDAO;
14     
15     public void init(){
16         System.out.println("init");
17     }
18     
19     public UserService(){}
20     
21     public UserService(UserDAO userDAO){
22         super();
23         this.userDAO = userDAO;
24     }
25     
26     public void addUser(User u){
27         this.userDAO.save(u);
28     }
29 
30     public UserDAO getUserDAO() {
31         return userDAO;
32     }
33 
34     @Resource(name="userDAOImpl")
35     public void setUserDAO(UserDAO userDAO) {
36         this.userDAO = userDAO;
37     }
38     
39     public void destroy(){
40         System.out.println("destroy");
41     }
42     
43 }
View Code

代码链接: http://pan.baidu.com/s/1i4GwEPn 密码: awdu

jar包链接: http://pan.baidu.com/s/1hs655SK 密码: 6h8x

posted @ 2017-05-24 10:52  流年如水烟雨随风  阅读(446)  评论(0编辑  收藏  举报