spring中AutoWired(9)

2016/1/16 15:22:02


1.Required

  • @Required注解适用于bean属性的setter方法
  • 这个注解仅仅表示,受影响的bean属性必须在配置时被填充,通过在bean定义或通过自动装配一个明确的属性值

2.AutoWired

  • 可以将@AutoWired注解为”传统”的setter方法
  • 也可以用在构造器或成员变量上
  • 默认情况下,如果因为找不到合适的bean将会导致autowiring失败抛出异常,刻意通过在注解上设置required属性为false

    @AutoWired(required=false)
    public void setXX(XX xx){
        this.xx = xx
    }
    
  • 每个类只能有一个构造器被标记为required=true
  • AutoWired的必要属性,建议使用@Required注解

XML:spring-autowired.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:p="http://www.springframework.org/schema/p" 
        xmlns:aop="http://www.springframework.org/schema/aop" 
        xmlns:tx="http://www.springframework.org/schema/tx" 
        xmlns:mvc="http://www.springframework.org/schema/mvc" 
        xmlns:context="http://www.springframework.org/schema/context" 
        xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
                            http://www.springframework.org/schema/context
                            http://www.springframework.org/schema/context/spring-context-3.0.xsd 
                            http://www.springframework.org/schema/aop
                            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
                            http://www.springframework.org/schema/tx
                            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
                            http://www.springframework.org/schema/mvc
                            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> 

        <context:annotation-config></context:annotation-config>
        <context:component-scan base-package="com.zjx"></context:component-scan>

</beans>

bean:

package com.zjx.dao.impl;

import org.springframework.stereotype.Repository;

import com.zjx.dao.InjectionDao;
@Repository
public class InjectionDaoImpl implements InjectionDao{

    @Override
    public void sava(String data) {
        System.out.println("保存数据:"+data);   
    }
}

package com.zjx.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zjx.dao.InjectionDao;
import com.zjx.service.InjectionService;
@Service
public class InjectionServiceImpl implements InjectionService {
    @Autowired
    private InjectionDao injectionDao;

    @Override
    public void save(String data) {
        System.out.println("Service接受参数:"+data);    
        data = data+":"+this.hashCode();
        injectionDao.sava(data);
    }

}

测试:

package com.zjx.interfaces.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;

import com.zjx.service.InjectionService;

@RunWith(BlockJUnit4ClassRunner.class)
public class TestAutoWired extends UnitTestBase {
    public TestAutoWired() {
        super("classpath:spring-autowired.xml");
    }
    @Test
    public void testAutoWired(){
        InjectionService service = super.getBean("injectionServiceImpl");
        service.save("this is autowired..");
    }
}

3.@AutoWired和@Resource注解的区别

转自:http://www.chinasb.org/archives/2011/06/2443.shtml 查看更多实例

Spring不但支持自己定义的@Autowired注解,还支持几个由JSR-250规范定义的注解,它们分别是@Resource、@PostConstruct以及@PreDestroy。

  • @Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,而@Resource默认按 byName自动注入罢了。
  • @Resource有两个属性是比较重要的,分是name和type,Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。
  • 所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。
  • 如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。

@Resource装配顺序
  

  1. 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
  2. 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
  3. 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
  4. 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配;

@Autowired 与@Resource的区别:

  1. @Autowired与@Resource都可以用来装配bean. 都可以写在字段上,或写在setter方法上
  2. @Autowired默认按类型装配(这个注解是属于spring的),默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用
  3. @Resource(这个注解属于J2EE的),默认安装名称进行装配,名称可以通过name属性进行指定,如果没有指定name属性,当注解写在字段上时,默认取字段名进行安装名称查找,如果注解写在setter方法上默认取属性名进行装配。当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。
  4. 推荐使用:@Resource注解在字段上,这样就不用写setter方法了,并且这个注解是属于J2EE的,减少了与spring的耦合。这样代码看起就比较优雅。

4.其他用途

  • 可以使用@Autowired注解那些众所周知的解析依赖性接口,比如:BeanFactory,ApplicationContext,Environment,ResourceLoader,ApplicationEventPublisher,MessageSource
  • 可以通过添加注解给需要该类型的数组的字段或方法,以提供ApplicationContext中的所有特定类型的bean
  • 可以用于装配key为String的Map
  • 如果希望数组有序,可以让bean实现org.springframwork.core.Ordered接口或使用@Order注解,但是Order只对数组有效,对map集合无效

5.注意

  • @Autowired是由Spring BeanPostProcessor处理的,所以不能在自己的BeanPostProcessor或BeanFactoryPostProcessor类型应用这些注解,这些类型必须通过XML或者Spring的@Bean注解加载

6.@Autowired装配操作

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:p="http://www.springframework.org/schema/p" 
        xmlns:aop="http://www.springframework.org/schema/aop" 
        xmlns:tx="http://www.springframework.org/schema/tx" 
        xmlns:mvc="http://www.springframework.org/schema/mvc" 
        xmlns:context="http://www.springframework.org/schema/context" 
        xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
                            http://www.springframework.org/schema/context
                            http://www.springframework.org/schema/context/spring-context-3.0.xsd 
                            http://www.springframework.org/schema/aop
                            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
                            http://www.springframework.org/schema/tx
                            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
                            http://www.springframework.org/schema/mvc
                            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> 

        <context:annotation-config></context:annotation-config>
        <context:component-scan base-package="com.zjx"></context:component-scan>

</beans>

package com.zjx.multibean;

public interface BeanInterface {

}

package com.zjx.multibean;

import org.springframework.stereotype.Component;

@Component
public class BeanOneImpl implements BeanInterface{

}

package com.zjx.multibean;

import org.springframework.stereotype.Component;

@Component
public class BeanTwoImpl implements BeanInterface{

}

package com.zjx.multibean;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author acer 定义一个包装类
 * 
 */
@Component
public class BeanInvoker {
    @Autowired
    private List<BeanInterface> list;
    @Autowired
    private Map<String, BeanInterface> map;

    public void say() {
        if (null != list && 0 != list.size()) {
            System.out.println("list...");
            for (BeanInterface bean : list) {
                System.out.println(bean.getClass().getName());
            }
        } else {
            System.out.println("List<BeanInterface> list is null!");
        }
        System.out.println();
        if (null != map && 0 != map.size()) {
            System.out.println("map...");
            for (Map.Entry<String, BeanInterface> entry : map.entrySet()) {
                System.out.println(entry.getKey() + "   "
                        + entry.getValue().getClass().getName());
            }
        } else {
            System.out.println("Map<String,BeanInterface> map is null!");
        }
    }
}

测试:
package com.zjx.interfaces.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;

import com.zjx.multibean.BeanInvoker;

@RunWith(BlockJUnit4ClassRunner.class)
public class TestMultiBean extends UnitTestBase{
    public TestMultiBean() {
        super("classpath:spring-autowired.xml");
    }

    @Test
    public void testMultiBean(){
        BeanInvoker invoker = super.getBean("beanInvoker");
        invoker.say();
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值