4-1 Spring Bean装配之Bean的定义及作用域的注解实现

Bean管理的注解实现及例子

  • Classpath扫描与组件管理
  • 类的自动检测与注册Bean
  • < context:annotation-config />
  • @Component,@Repository,@Service,@Controller
  • @Required
  • @Autowired
  • @Qualifier
  • @Resource

Classpath扫描与组件管理

  • 从Spring3.0开始,Spring JavaConfig项目提供了很多特性,包括使用java而不是XML定义bean,比如@Configuration,@Bean,@Import,@DependsOn
  • @Component是一个通用注解,可用于任何bean
  • @Repository,@Service,@Controller是更有针对性的注解
    – @Repository通常用于注解DAO类,既持久层
    – @Service通常用于注解Service类,既服务层
    – @Controller通常用于Controller类,既控制层(MVC)

元注解(Meta-annotations)

  • 许多Spring提供的注解可以作为自己的代码,既“元数据注解”,元注解是一个简单的注解,可以应用到另一个注解

import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
import java.lang.annotation.*;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
}
  • 除了value(),元注解还可以有其它的属性,允许定制
package com.torey.resource;

import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;

import java.lang.annotation.*;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
    ScopedProxyMode proxyModel() default ScopedProxyMode.DEFAULT;
}

类的自动检测及Bean的注册

  • Spring可以自动检测类并注册Bean到ApplicationContext中

< context:annotation-config />

  • 通过在基于XML的Spring配置如下标签(请注意包含上下文命名空间)
  • < context:annotation-config />仅会查找在同一个applicationContext中的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.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config/>
</beans>

类的自动检测及Bean的注册

  • 为了能够检测这些类并注册响应的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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
      <!--组件扫描-->
    <context:component-scan base-package="com.example"/>
</beans>
  • < context:component-scan >包含< context:annotation-config >,通常在使用前者后,不用再使用后者
  • AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor也会被包含进来

使用过滤器进行自定义扫描

  • 默认情况下,类被自动发现并注册bean的条件是:使用@Component,@Repository,@Service,@Controller注解或者使用@Component的自定义注解
  • 可以通过过滤器修改上面的行为,如:下面例子的XML配置忽略所有的@Repository注解并用"Stub"代替
<?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">
    <context:component-scan base-package="com.example">
    
        <context:include-filter type="regex" expression=".*Stub.*Repository"/>
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
    </context:component-scan>
</beans>
  • 还可以使用use-default-filters=“false” 禁用自动发现与注册

定义Bean

  • 扫描过程中组件被自动检测,那么Bean名称是由BeanNameGenerator生成的(@Component,@Repository,@Service,@Controller都会有个name属性用于显示设置Bean Name),如果不指定Bean Name,则以类名称的首字母小写作为bean Name.
@Service("myMovieLister")
public class SimpleMovieLister{}
  • 可自定义bean命名策略,实现BeanNameGenerator接口,并一定要包含一个无参数构造函数
<?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">
    <context:component-scan base-package="com.torey.resource" 
                            name-generator="org.xxx.myNameGenerator"/>
</beans>

作用域(Scope)

  • 通常情况下自动查找的Spring组件,其scope实singleton,Spring2.5提供了一个标识scope的注解@Scope
@Scope("prototype")
@Repository
public class MovieFinderImpl implements MovieFinder{
}
  • 也可以自定义scope策略,实现ScopeMetadataResolver接口并提供一个无参构造器
<?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">
    <context:component-scan base-package="com.torey.resource" 
                            scope-resolver="org.xxx.myscopeGenerator"/>
</beans>

代理方式

  • 可以使用scoped-proxy属性指定代理,有三个值可选:no,interfaces,targetClass
<beans>
   <context:component-scan base-package="org.example" 
                            scoped-proxy="interfaces"/>
</beans>

Bean定义及作用域

例子

在这里插入图片描述

package com.torey.beanannotation;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @ClassName:BeanAnnotation
 * @Description:
 * @author: Torey
 */
//@Component("bean1")
@Component //如果不指定名称,默认首字母小写
@Scope("prototype") //设置bean的作用域,默认是单例
public class BeanAnnotation {
    public void say(String ary) {
        System.out.println("BeanAnnotation的say方法:" + ary);
    }
}
<?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">
    <context:component-scan base-package="com.torey.beanannotation"/>
</beans>
package com.torey.springtest.base;

import org.junit.After;
import org.junit.Before;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;

/**
 * @ClassName:UnitTestBase
 * @Description:
 * @author: Torey
 */
public class UnitTestBase {
    public UnitTestBase(){}
    private String springXmlPath;
    private ClassPathXmlApplicationContext applicationContext;
    public UnitTestBase(String springXmlpath){
        this.springXmlPath=springXmlpath;
    }
    @Before
    public void before(){
        if (StringUtils.isEmpty(springXmlPath)) {
            springXmlPath="classpath*:spring-*.xml";
        }
        applicationContext= new ClassPathXmlApplicationContext(springXmlPath.split("[,\\s]"));
        applicationContext.start();
    }
    @After
   public void after(){
        applicationContext.destroy();
   }
   public Object getBean(String beanId){
       return applicationContext.getBean(beanId);
   }
}

package com.torey.springtest.bean;

import com.torey.beanannotation.BeanAnnotation;
import com.torey.springtest.base.UnitTestBase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;

import java.io.IOException;

/**
 * @ClassName:TestResource
 * @Description:
 * @author: Torey
 */
@RunWith(BlockJUnit4ClassRunner.class)
public class TestBeanAnnotation extends UnitTestBase {
    public TestBeanAnnotation(){
        super("classpath:spring-beanannotation.xml");
    }
    @Test
    public void testAnnotation(){
        //不指定beanName,默认首字母小写
       // BeanAnnotation bean =(BeanAnnotation) super.getBean("bean1");
        BeanAnnotation bean =(BeanAnnotation) super.getBean("beanAnnotation");
        BeanAnnotation bean1 =(BeanAnnotation) super.getBean("beanAnnotation");
        bean.say("111");
        System.out.println(bean.hashCode());
        System.out.println(bean1.hashCode());

    }
}

根据慕课网 moocer老师的spring课程 整理

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值