Autowired注解的使用

1.
Autowired可以将@Autowired注解为传统的setter方法,也可以用于构造器或成员变量在默认的情况下,如果找不到合适的bean将会导致aotowired失败或者是抛出异常, 但是可以通过下面的代码来避免。

public class SimpleMovieLister{
    private MovieFinder movieFinder;
    @Autowired(required=flase)
    public void setMovieFinder(MovieFinder movie){
        this.movieFinder = movie;
    }
}

每个类中只能有一个构造器被表示为required = true
在spring的官方文档中如果是必要的属性,建议使用@required注解

2.
通过@Autowired的注解可以使用list集合或者是map集合来输出或者是使用这个类中的资源。

public interface BeanInterface {
//定义的一个接口
}

@Order(2)//可以更改排序的位置
@Component
public class One_interface implements BeanInterface{
    //实现接口的一个类
}

@Order(1)
@Component
public class Two_interface implements BeanInterface{
    //实现接口的一个类
}

@Component
public class BeanInvoker {
    @Autowired
    private List<BeanInterface> list;

    public void say(){
        if(list != null && list.size() != 0)
            for (BeanInterface beanInterface : list) {
                System.out.println(beanInterface.getClass().getName());
            }
        else
            System.out.println("not null");
    }
}

@RunWith(BlockJUnit4ClassRunner.class)
public class TestInterface {
    public TestInterface() {}
    @Test
    public void say(){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-interface.xml");
        BeanInvoker beaninvoker = ctx.getBean("beanInvoker", BeanInvoker.class);
        beaninvoker.say();
    }
}

//最后就是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.xsd 
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        <!--这个是在这个包里面查找bean-->
        <context:component-scan base-package="spring_test06"></context:component-scan>
 </beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值