Spring IOC使用(3) 基于注解管理bean

来源:互联网 发布:淘宝阿里旺旺打不开 编辑:程序博客网 时间:2024/05/16 12:40

1. context:component-scan标签

<!-- 用于扫描类,并注册bean --><!-- base-package属性,可以扫描一些包(包括子包)name-generator属性,自定义命名策略,实现BeanNameGenerator接口的类,必须包含无参数构造器scope-resolver属性,自定义scope策略,实现ScopeMetadataResolver接口--><context:component-scan base-package="com.emmairving.spring.annotation">    <!-- type有五种:annotation, assignable, aspectj, regex, custom -->    <context:include-filter type="regex" expression="com.emmairving.spring.annotation.*"/>    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>     <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>       <context:exclude-filter type="regex" expression="com.emmairving.spring.annotation.son.*"/></context:component-scan><!-- 有了<context:component-scan>之后,基本都不使用以下配置 --><context:annotation-config/>

2. Autowired注解

//可以指定bean的id@Service("master")public class Master {    //Autowired注解默认是通过类型来自动装载,如果需要指定名称,可以与Qualifier注解配合使用    //Autowired注解的required默认为true,如果没有能注入对应的bean就会报错。设置为false之后,就不会报错。    //Autowired可以修饰构造器、方法    @Autowired(required=false)    //Qualifier注解可以指定要注入bean的名称    @Qualifier("slave")    private Slave slave;    //可以用Autowired注解中所周知的解析依赖接口,如ApplicationContext    @Autowired    private ApplicationContext ctx;    //如果有多个符合条件的bean,可以用数组、集合类型等    //如果不是集合类型,也不会报错,会选择众多符合条件bean中的一个注入    @Autowired    private Slave[] slaves;    public void test() {        Member member = ctx.getBean("member1",Member.class);        System.out.println(member);        System.out.println(slaves.length);        System.out.println("My Slave "+slave);    }}@Controller("slave")public class Slave {    private String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Slave() {        name="lucy";    }    @Override    public String toString() {        return "Slave [name=" + name + "]";    }}

3. 参考资料

  • 慕课网与极客学院的视频课程
0 0
原创粉丝点击