Spring基于注解的零配置支持

一、搜索Bean类
为了不再使用Spring的配置文件来配置任何bean实例,Spring自动搜索某些路径下的Java类,并将这些java类注册成Bean实例
Spring提供了如下几个Annotation来标注Spring Bean,目的让Spring知道应该把哪些Java类当成Bean类处理。

  1. @Conponent:标注一个普通的Spring Bean 类
  2. @Controller:标注一个控制器组件类
  3. @Service:标注一个业务逻辑组件类
  4. @Repository:标注一个Dao组件类
    二、使用实例
package com.home.bean;
/**
 * 定义一个接口
 */
public interface Axe {
   public String chop();
}

package com.home.bean;
import org.springframework.stereotype.Component;
@Component
public class SteelAxe implements Axe{

    public String chop() {
        // TODO Auto-generated method stub
        return "钢斧砍柴真的很快";
    }
}

package com.home.bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
//指定该bean实例的作用域为prototype,不指定默认为singleton
@Scope("prototype")
//指定该类作为spring Bean,Bean实例名为axe
@Component("stoneAxe")
public class StoneAxe implements Axe{
    public String chop() {
        // TODO Auto-generated method stub
        return "石斧砍柴真的很慢";
    }
}

配置文件:
    <context:annotation-config/>
    <!-- 自动扫描指定包及其子包下的所有bean类 -->
    <context:component-scan base-package="com.home.bean">
    <!-- 只是以Axe结尾的类当成Spring容器中的bean -->
    <!-- type:指定过滤器类型
         1.annotation:Annotation过滤器,该过滤器需要指定一个Annotation名,如lee.AnnotationTest
         2.assignable:类过滤器,该过滤器直接指定一个java类
         3.regex,正则表达式过滤器,指定过滤规则,使用如下
         4.aspectJ:AspectJ过滤器,如org.example.*Service+
     -->
    <context:include-filter type="regex" expression=".*Axe"/>
    </context:component-scan>
测试类:
package spring;
import java.util.Arrays;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanTest {
    public static void main(String[] args) {
        //创建spring容器
         ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
         System.out.println("Bean实例名称:"+Arrays.toString(ctx.getBeanDefinitionNames()));
    }
}
发布了91 篇原创文章 · 获赞 7 · 访问量 6万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章