@Component 注解

Posted 流年如水~烟雨随风

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了@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

以上是关于@Component 注解的主要内容,如果未能解决你的问题,请参考以下文章

HarmonyOS鸿蒙学习笔记@Component注解自定义组件简单说明

HarmonyOS鸿蒙学习笔记@Component注解自定义组件简单说明

spring注解注入:<context:component-scan>详解(转)

注解 @Resource与@Autowired与@Component的使用

注解service和component的区别

@Component注解的用法