spingboot系统配置自动装配

使用SpringBootApplication作为springboot启动类代码一般如下:

@SpringBootApplication
public class SpringBootApplicationDemo {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApplicationDemo.class,args);

    }
}

先看启动时的SpringBootApplication

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
    @AliasFor(
        annotation = EnableAutoConfiguration.class
    )
    Class<?>[] exclude() default {};

    @AliasFor(
        annotation = EnableAutoConfiguration.class
    )
    String[] excludeName() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackages"
    )
    String[] scanBasePackages() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackageClasses"
    )
    Class<?>[] scanBasePackageClasses() default {};
}


除去元注解,包含了三个注解:@SpringBootConfiguration,@EnableAutoConfiguration和@ComponentScan。

SpringBootConfiguration

/**
 * Indicates that a class provides Spring Boot application
 * {@link Configuration @Configuration}. Can be used as an alternative to the Spring's
 * standard {@code @Configuration} annotation so that configuration can be found
 * automatically (for example in tests).
 * <p>
 * Application should only ever include <em>one</em> {@code @SpringBootConfiguration} and
 * most idiomatic Spring Boot applications will inherit it from
 * {@code @SpringBootApplication}.
 *
 * @author Phillip Webb
 * @since 1.4.0
 */

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
}

根据注释@Configuration注解用允许在spring中倒入注册额外bean
第二个
@EnableAutoConfiguration,字面理解就是可以自动配置bean
第三个ComponentScan

/**
 * Configures component scanning directives for use with @{@link Configuration} classes.
 * Provides support parallel with Spring XML's {@code <context:component-scan>} element.
 *
 * <p>Either {@link #basePackageClasses} or {@link #basePackages} (or its alias
 * {@link #value}) may be specified to define specific packages to scan. If specific
 * packages are not defined, scanning will occur from the package of the
 * class that declares this annotation.
 *
 * <p>Note that the {@code <context:component-scan>} element has an
 * {@code annotation-config} attribute; however, this annotation does not. This is because
 * in almost all cases when using {@code @ComponentScan}, default annotation config
 * processing (e.g. processing {@code @Autowired} and friends) is assumed. Furthermore,
 * when using {@link AnnotationConfigApplicationContext}, annotation config processors are
 * always registered, meaning that any attempt to disable them at the
 * {@code @ComponentScan} level would be ignored.
 *
 * <p>See {@link Configuration @Configuration}'s Javadoc for usage examples.
 *
 * @author Chris Beams
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @since 3.1
 * @see Configuration
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan {


根据注释

  • <p>Either {@link #basePackageClasses} or {@link #basePackages} (or its alias
  • {@link #value}) may be specified to define specific packages to scan. If specific
  • packages are not defined, scanning will occur from the package of the
  • class that declares this annotation.

如果没有指定basePackageClasses或basePackages 只会扫描使用该注解修饰的类所在的包和改类以下的子包,如果要扫描其他包需要用basePackages来指定:如这样使用注解:@SpringBootApplication(scanBasePackages = {"com.test.**"})

所以默认使用方法:SpringBootApplication注解作用的主程序类需要在根包,spring对类的默认仅涵盖主程序所在包及子包.
conditionalOn解释:
@ConditionalOnBean(仅仅在当前上下文中存在某个对象时,才会实例化一个Bean)
@ConditionalOnClass(某个class位于类路径上,才会实例化一个Bean)
@ConditionalOnExpression(当表达式为true的时候,才会实例化一个Bean)
@ConditionalOnMissingBean(仅仅在当前上下文中不存在某个对象时,才会实例化一个Bean)
@ConditionalOnMissingClass(某个class类路径上不存在的时候,才会实例化一个Bean)
@ConditionalOnNotWebApplication(不是web应用)
@ConditionalOnClass:该注解的参数对应的类必须存在,否则不解析该注解修饰的配置类;
@ConditionalOnMissingBean:该注解表示,如果存在它修饰的类的bean,则不需要再创建这个bean;可以给该注解传入参数例如@ConditionOnMissingBean(name = "example"),这个表示如果name为“example”的bean存在,这该注解修饰的代码块不执行。
如下,没有加载redisTemplate的话,不会执行启动bean

    @Bean
    @ConditionalOnClass(name = "org.springframework.data.redis.core.RedisTemplate")
    public ServiceBean getServiceBean(){
        ServiceBean serviceBean = new ServiceBean();
        serviceBean.setId("1");
        serviceBean.setName("test");
        System.out.println("我家在了serviceBean");
        return serviceBean;
    }

外部参数配置:
启动时使用命令行传参:java -jar app.jar --name="test"
springBoot配置信息中特殊值:SPRING_APPLICATION_JSON='{"name":"test"}'
如果是web应用,可以读取ServletConfig init参数
如果是web应用,可以读取SerletContext init参数
JNDI属性来自java:comp/env
java系统属性(System.getProperties())
配置文件application.properties,application.yml,application-{profile}.properties,application-(profile).yml
@PropertiySource注解导入的配置:@PropertySource(value={"person.properties})
程序入口通过SpringApplication.setDefaultProperties方法设定的参数配置

@Component
@PropertySource(value = "serviceBean.properties")
public class PropertiesBean {

    @Value("${id}")
    private String id;

    @Value("${name}")
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

profile机制:隔离环境,使配置仅在某个特定环境中使用

配置文件存放配置:
1.当前项目运行的盘符/config目录下:file:./config/
2.当前项目运行的目录下:file:./
3.classpath目录下config:classpath/config
4.classpath目录下:classpath:
以上按优先级顺序排列

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring入门使用Spring容器Spring容器使用ApplicationContextApplication...
    渐丶忘阅读 5,305评论 0 4
  • 深入使用 Spring两种后处理器Bean 后处理器容器后处理器属性占位符配置器重写占位符配置器Spring 的自...
    渐丶忘阅读 4,832评论 0 1
  • Spring 技术笔记Day 1 预热知识一、 基本术语Blob类型,二进制对象Object Graph:对象图...
    OchardBird阅读 4,617评论 0 2
  • 拷贝刚才的工程demo-json,改为demo-javaconfig springboot自动配置 入口类 观察之...
    RobertLiu123阅读 3,523评论 0 0
  • 本来是准备看一看Spring源码的。然后在知乎上看到来一个帖子,说有一群**自己连Spring官方文档都没有完全读...
    此鱼不得水阅读 11,838评论 4 21

友情链接更多精彩内容