Spring Boot 2.0之走向自动装配

Spring 模式注解装配

模式注解

模式注解是一种用于声明在应用中扮演“组件”角色的注解。如 Spring Framework 中的 @Repository 标注在任何类上 ,用于扮演仓储角色的模式注解。
@Component 作为一种由 Spring 容器托管的通用模式组件,任何被 @Component 标注的组件均为组件扫描的候选对象。类似地,凡是被 @Component 元标注(meta-annotated)的注解,如 @Service ,当任何组件标注它时,也被视作组件扫
描的候选对象

模式注解举例

Spring Framework 注解 场景说明 起始版本
@Repository 数据仓储模式注解 2.0
@Component 通用组件模式注解 2.5
@Service 服务模式注解 2.5
@Controller Web 控制器模式注解 25
@Configuration 配置类模式注解 3.0

以上其余四个注解,都标注了@Component

自定义模式注解

@Component “派生性
/**
 * 一级 {@link Repository @Repository}
 */

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repository
public @interface FirstLevelRepository {
    String value() default "";
}
  • @Component

    • @Repository

      • @FirstLevelRepository

使用自定义注解@FirstLevelRepository的类也会被注册到容器中去

/**
 * {@link FirstLevelRepository}
 */

@FirstLevelRepository(value = "myFirstLevelRepository")
public class MyFirstLevelRepository {
}
@Component “层次性”
/**
 * 二级 {@link FirstLevelRepository}
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@FirstLevelRepository
public @interface SecondLevelRepository {

    String value() default "";
}
  • @Component

    • @Repository

      • @FirstLevelRepository

        • @SecondLevelRepository

使用自定义注解@SecondLevelRepository的类也会被注册到容器中去

/**
 * {
  {@link SecondLevelRepository}}
 * Created by Yuk on 2019/3/9.
 */

@SecondLevelRepository(value = "mySecondLevelRepository")
public class MySecondLevelRepository {
}

装配方式

需要有一种配置方式来发现这些被模式注解标注的类

xml配置context:component-scan方式
<?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/springcontext.xsd">
<!-- 激活注解驱动特性 -->
<context:annotation-config />
<!-- 找寻被 @Component 或者其派生 Annotation 标记的类(Class),将它们注册为 Spring Bean -->
<context:component-scan base-package="com.yk.dive.in.spring.boot" />
</beans>

@ComponentScan 方式

@ComponentScan(basePackages = "com.yk.dive.in.spring.boot")
public class SpringConfiguration {
...
}

Spring @Enable 模块装配

Spring Framework 3.1 开始支持”@Enable 模块驱动“。所谓“模块”是指具备相同领域的功能组件集合, 组合所形成一个独立的单元。比如 Web MVC 模块、AspectJ代理模块、Caching(缓存)模块、JMX(Java 管 理扩展)模块、Asy

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值