Spring 核心注解

2019-08-26  本文已影响0人  xiaolyuh

@Configuration 配置类注解

声明一个类是配置类,等同于配置文件中的applicationcontext.xml
加载Spring配置的两种方式:

  1. ClassPathXmlApplicationContext XML方式
ApplicationContext app = new ClassPathXmlApplicationContext("applicationcontext.xml");
  1. AnnoatationConfigApplicationContext 注解方式
ApplicationContext app = new AnnotationConfigApplicationContext(MainConfig.class);

@ComponentScan 包扫描注解

@ComponentScan(value="com.enjoy.cap2")表示扫描此目录下的包。

参数说明:

扫描规则如下:

示例:

/**
 * 包扫描测试类
 *
 * @author yuhao.wang3
 * @since 2019/8/24 10:39
 */
@Configuration
@ComponentScan(value = "com.xiaolyuh.component.scan", includeFilters = {
        // 只扫描Controller注解的 Bean
        @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class}),
        // 只扫描特定的类
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {TestService.class}),
        // 使用特定的过滤规则
        @ComponentScan.Filter(type = FilterType.CUSTOM, classes = {CustomTypeFilter.class})
}, useDefaultFilters = false)
public class ComponentScanConfig {

}
@Test
public void contextTest() {
    String[] names = context.getBeanDefinitionNames();
    Arrays.stream(names).forEach(System.out::println);
}

输出结果:

componentScanConfig
testController
customTypeFilter
customTypeFilterService
testService

TestDao就没有被加载,完整代码请到仓库拉取

@Bean 声明一个Bean,并放到Spring容器

将一个普通类声明成一个Spring里面的Bean。等同于XML中的 <bean id="xxx" class="xxx"/>Spring bean 的初始化和销毁的三种方式和执行顺序
可参考这里。

@Scope 描述的是Spring容器如何创建Bean的实例的

示例:

@Configuration
public class ScopeConfig {

    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    @Bean("scopeTestBean")
    public ScopeTestBean scopeTestBean() {
        return new ScopeTestBean();
    }
}

@Lazy

在 Spring 单例模式下,默认在容器初始化的时候创建Bean,如果加了@Lazy注解,那么容器启动的时候不会去实例化对象,而是在第一次使用Bean的时候才回去创建对象。

示例:

@Configuration
public class LazyConfig {

    @Lazy
    @Bean
    public LazyTestBean lazyTestBean() {
        return new LazyTestBean();
    }
}

Spring 声明Bean的注解

Spring 注入Bean的注解:

声明Spring Bean和注入Bean的几种常用注解和区别可参考这里。

@Conditional 条件注入

当引入@Conditional时, 容器可以选择性的注册bean。具体可以参考:Spring 条件注解(@Conditional)

@Import注册bean

@Import注解一次可以注入多个Bean,默认使用全类名作为Bean id;而@Bean一次只能注入一个Bean,默认使用方法名作为Bean id。
详情可参考:声明Spring Bean和注入Bean的几种常用注解和区别

源码

https://github.com/wyh-spring-ecosystem-student/spring-boot-student/tree/releases

spring-boot-student-spring 工程

layering-cache

为监控而生的多级缓存框架 layering-cache这是我开源的一个多级缓存框架的实现,如果有兴趣可以看一下

上一篇 下一篇

猜你喜欢

热点阅读