@Autowired
通过 @Autowired的使用来消除 set ,get方法 - Spring 2.5 JPA hibernate 使用方法的点滴整理

我们编写spring 框架的代码时候。一直遵循是这样一个规则:所有在spring中注入的bean 都建议定义成私有的域变量。并且要配套写上 get 和 set方法。虽然可以通过eclipse等工具来自动生成。但是还是会引起程序阅读性上的不便。那么既然注解这么强大。是否可以也把他精简掉呢?

当 然可以。这个标签就是@Autowired

Spring 2.5 引入了 @Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。

要实现我们要精简程序的目的。需要这样来处理:

* 在applicationContext.xml中加入:
    <!-- 该 BeanPostProcessor 将自动对标注 @Autowired 的 Bean 进行注入 -->  
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

* 修改在原来注入spirng容器中的bean的方法。
     在域变量上加上标签@Autowired,并且去掉 相应的get 和set方法

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import com.firemax.test.hibernate.AlcorTCitys;
import com.firemax.test.hibernate.AlcorTCitysDAO;
import com.firemax.test.hibernate.AlcorTCountries;
import com.firemax.test.hibernate.AlcorTCountriesDAO;
import com.firemax.test.hibernate.AlcorTProvinces;
import com.firemax.test.hibernate.AlcorTProvincesDAO;
import com.firemax.test.hibernate.AlcotTDistrict;
import com.firemax.test.hibernate.AlcotTDistrictDAO;
public class CountryService {
     private static Log logger = LogFactory.getLog(CountryService.class);
     @Autowired
     private AlcorTCountriesDAO alcorTCountriesDAO;
     @Autowired
     private AlcorTProvincesDAO alcorTProvincesDAO;
     @Autowired
     private AlcorTCitysDAO          alcorTCitysDAO;
     @Autowired
     private AlcotTDistrictDAO       alcotTDistrictDAO;
     public CountryService(){
     }
    
     public void updateCountry(AlcorTCountries alcorTCountries ) throws Exception{
         this.alcorTCountriesDAO.update(alcorTCountries);
     }
     ....
     //这里去掉了哪些DAO 变量的get 和set 方法。
}

* 在applicatonContext.xml中 把原来 引用的<porpery >标签也去掉。

<bean id="CountryService" class="com.firemax.test.service.CountryService">
                  <property name="alcorTCountriesDAO" ref="AlcorTCountriesDAO" />
                  <property name="alcorTProvincesDAO" ref="AlcorTProvincesDAO" />
                  <property name="alcorTCitysDAO" ref="AlcorTCitysDAO" />
                 <property name="alcotTDistrictDAO" ref="AlcotTDistrictDAO" />
          </bean>

修改成

<bean id="CountryService" class="com.firemax.test.service.CountryService">
                
         </bean>

当然,我们也可以在构造函数上使用@Auwowired 注解 。如果构造函数有两个入参,分别是 bean1 和 bean2,@Autowired 将分别寻找和它们类型匹配的 Bean,将它们作为 CountryService (Bean1 bean1 ,Bean2 bean2) 的入参来创建 CountryService Bean。

@Resource

Spring使用@Resource注解完成属性装配

使用Field注入(用于注解方式)
注入依赖对象可以采用手工装配或自动装配,在实际应用中建议使用手工装配,因为自动装配会产生未知情况,开发人员

无法预见最终的装配结果
1.手工装配依赖对象
2.自动装配依赖对象

手工装配依赖对象,这汇总方式中又有两种编程方式
1.在xml配置文件中,通过在bean节点下配置 如
<bean id="personDao" class="com.qn.service.impl.PersonDaoBean"></bean>
 <bean id="personService" class="com.qn.service.impl.PersonServiceBean">
 <constructor-arg index="0" type="com.qn.dao.PersonDao" ref="personDao"></constructor-arg>
 <constructor-arg index="1" value="齐宁"></constructor-arg>
 </bean>
2.在java代码中使用@Autowired或@Resource注解方式进行装配,但我们需要在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/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd">
          <context:annotation-config/>
</beans>

这个配置隐式注册了多个对注释进行解析处理的处理器:AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessorPersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor
注:@Resource注解在spring安装目录的common-annotations.jar

.在java代码中使用@Autowired或@Resource注解方式进行装配,但我们需要在xml配置文件中配置如下信息
这个配置隐式注册了多个对注释进行解析处理的处理器:AutowiredAnnotationBeanPostProcessor,

CommonAnnotationBeanPostProcessorPersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcesso

r
注:@Resource注解在spring安装目录的common-annotations.jar
在java代码中使用@Autowired或@Resource注解方式进行装配,这两个注解的区别是:@Autowired默认按类型装配。

@Resource默认按名车装配,,当找不到与名称匹配的bean才会按类型装配
@Autowired
用于字段上面
@Autowired
用于属性的setter()方法上
@Autowired注解是按类型装配依赖对象,默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它required的

属性为false。如果想使用按名称装配,可以结合@Qualifier注解一起使用。如下:
@Autowired @Qualifier(“personDaoBean”)
private PersonDao personDao;
@resource注解和@Autowiredyiyang ,也可以标注在字段或属性的setter方法上,但默认的是按名称装配,名称可以通过

@rResource的name属性指定,如果没有指定name属性,当注解标注在字段上面,即默认去字段的名称作为bean名称寻找依

赖对象,当注解标注在属性的setter方法上,即默认取属性的名称作为bean名称寻找依赖对象
@Resource(name=“personDaoBean”)
private PersonDao personDao;//用于字段上
注意:如果没有指定name属性,并且按照默认的名称仍然找不到依赖对象时,@Resource注解会回退到按类型装配,但一

旦指定了name属性,就只能按名称装配了

事例

1.定义接口PersonDao

package com.qn.dao;

public interface PersonDao {
     void add();
}

2.定义接口PersonService

package com.qn.dao;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public interface PersonService {
 void save();

}

3.定义类PersonDaoBean实现PersonDao

package com.qn.service.impl;

import com.qn.dao.PersonDao;

public class PersonDaoBean implements PersonDao{

public void add() {
  System.out.println("PersonDaoBean的添加方法");
 }

}

4.定义类PersonServiceBean实现PersonService

package com.qn.service.impl;

import javax.annotation.Resource;

import com.qn.dao.PersonDao;
import com.qn.dao.PersonService;

public class PersonServiceBean implements PersonService {
    @Resource
    private PersonDao personDao;
    private String name;
    public PersonServiceBean(){}
 public PersonServiceBean(PersonDao personDao, String name) {
  this.personDao = personDao;
  this.name = name;
 }

public void save(){
  personDao.add();
  System.out.println(name);
 }
}

5.在bean中进行配置

<?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/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd">
          <context:annotation-config/>
          <bean name="personDao" class="com.qn.service.impl.PersonDaoBean"></bean>
          <bean name="personService" class="com.qn.service.impl.PersonServiceBean"></bean>
</beans>

6.在test中进行测试

package com.qn.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.qn.dao.PersonService;

public class test {

public static void main(String []args){
  AbstractApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
  PersonService personService=(PersonService) ctx.getBean("personService");
  personService.save(); 
 }
}

结果

这个时候在PersonServiceBean类中

@Resource
    private PersonDao personDao;

的注解先是按名称看beans.xml中看是否存在personDao名称如果存在则显示结果

如果beans.xml中没有personDao名字呢?

如下配置

<bean name="personDaoxxxx" class="com.qn.service.impl.PersonDaoBean"></bean>
          <bean name="personService" class="com.qn.service.impl.PersonServiceBean"></bean>

结果

这个时候会按类型查找看是否有类型是PersonDao

当然也可以注明name

@Resource(name="personDaoxxxx")
    private PersonDao personDao;

结果

也可以把注解写到sett方法上

@Resource
 public void setPersonDao(PersonDao personDao) {
  this.personDao = personDao;
 }

结果

转载于:https://www.cnblogs.com/zghull/archive/2012/06/27/2565480.html

@Autowired、@Resource相关推荐

  1. Spring注解@Component、@Repository、@Service、@Controller,@Autowired、@Resource用法

    一.Spring定义bean,@Component.@Repository.@Service 和 @Controller Spring 2.5 中除了提供 @Component 注释外,还定义了几个拥 ...

  2. 【Spring注解系列13】Spring自动装配总结:@Autowired、@Resource、@Qualifier、@Inject

    目录 1.@Autowired.@Resource.@Qualifier.@Inject 1).@Autowired 2).@Resource与@Inject 3). @Autowired参数取值 2 ...

  3. Spring下的@Inject、@Autowired、@Resource注解区别(转)

    1.@Inject javax.inject JSR330 (Dependency Injection for Java) 这是JSR330中的规范,通过AutowiredAnnotationBean ...

  4. Spring @Autowired、@Resource、@Required、@Component、@Repository、@Service、@Controller注解的用法和作用...

    Spring @Autowired,@Resource,@Required注解的用法和作用 Spring中 @Autowired标签与 @Resource标签 的区别 Spring注解@Compone ...

  5. Spring5:@Autowired注解、@Resource注解和@Service注解

    转载:http://www.cnblogs.com/xrq730/p/5313412.html 什么是注解 传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop.事物,这么做有 ...

  6. Spring中@Resource与@Autowired、@Qualifier的用法与区别

    Spring中@Resource与@Autowired.@Qualifier的用法与区别 1.@Autowired与@Resource都可以用来装配bean. 都可以写在字段上,或写在setter方法 ...

  7. 同一接口有多个实现类,怎么来注入一个指定的实现?@Resource、@Autowired、@Qualifier

    如果一个接口有2个以上不同的实现类, 那么如何Autowire一个指定的实现 1:首先,UserService接口有两个实现类 UserService1和 UserService2 UserServi ...

  8. Spring中@Autowired、@Qualifier、@Resource的区别

    转自: Spring中@Autowired.@Qualifier.@Resource的区别_老周聊架构的博客-CSDN博客_qualifier和resource区别1.@Autowired@Autow ...

  9. spring注解( @Autowired、@Qualifier、@Resource、@PostConstruct、@PreDestroy、 @Component、@Scope)-描述的比较清楚

    概述: 注释配置相对于 XML 配置具有很多的优势: 它可以充分利用 Java 的反射机制获取类结构信息,这些信息可以有效减少配置的工作.如使用 JPA 注释配置 ORM 映射时,我们就不需要指定 P ...

最新文章

  1. Contest Hunter CH6201 走廊泼水节 最小生成树 Kruskal
  2. 通过printf设置Linux终端输出的颜色和显示方式
  3. Java 对象引用以及对象赋值
  4. 马云致投资者公开信:大数据云计算是阿里未来十年核心战略之一
  5. 【BZOJ1043】下落的圆盘 [计算几何]
  6. 124angular1实现无限表单(仅供自己看)
  7. ssm中spring mvc找不到控制器,报错404
  8. SLF4J和Logback日志框架详解
  9. mysql 字段值1_2_3 如何查询3是否存在?_MySQL根据col1中的值是否存在于col2中以及col3是否=值来更新col4...
  10. OFFICE技术讲座:双层字体引擎的提出
  11. 行政组织理论-阶段测评3
  12. 尝试运行项目时出错,无法启动程序 , 由于应用程序配置不正确,未能启动此应用程序。请查看清单文件以查找可能的错误。
  13. Code.V光学设计学习(一)——入门介绍
  14. 计算机课件制作技能,PPT技能制作大比拼
  15. 民进自强进修学院 计算机,#民进自强#中复班学生周记摘录
  16. 使用springboot+vue+element-ui模仿蓝墨云班课
  17. 菜鸟应用-手机应用在线制作平台,手机应用,APP开发,手机软件开发
  18. 最大的计算机计数单位,计数单位最大只知道亿?也许更大的计数单位能让你笑出声。...
  19. 怎么批量修改文件夹里照片的名字
  20. 星星之火-10:移动通信中的用户标识大汇总以及在手机呼叫流程中的使用--MSISDN,MSRN,IMSI,TMSI,PCI, CGI

热门文章

  1. nokia 计算机手机,NOKIA手机与电脑的数据线连接
  2. android内部类broadcastreceiver,android 公开静态内部类BroadcastReceiver
  3. 摄像头夜间拍摄画面有拖影_让客厅秒变健身房,OPPO智能电视R1+摄像头上手体验...
  4. 基于java springboot+mybatis OA办公自动化系统设计和实现
  5. mysql身份验证失败_SMTP身份验证失败PAM-MySQL无法进行身份验证
  6. pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org',
  7. Java 数组排序及元素查找
  8. 没有bug队——加贝——Python 59,60
  9. 整数线性规划实现(matlab分枝界定法)
  10. arm linux sms,基于arm处理器的手机短消息加密系统 encryption system for sms based on arm.pdf...