SpringBoot-annotation
/Enable the ConfigurationProperties annotated beans
@SpringBootApplication @EnableConfigurationProperties({ConfigBean.class,TestConfigBean.class}) @ImportResource({"classpath:some-application.xml"})
@Value("${mrbird.blog.name}") private String name;
@ConfigurationProperties(prefix="mrbird.blog")
//Specify the property source and its prefix
@Configuration @ConfigurationProperties(prefix="test") @PropertySource("classpath:test.properties") @Component
Disabling Specific Auto-configuration Classes
@Configuration @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) public class MyConfiguration { }
Specify the packaged scaned by spring same as <context:component-scan>
You can add @ComponentScan
without any arguments. All of your application components (@Component
, @Service
, @Repository
, @Controller
etc.) are automatically registered as Spring Beans.
@ComponentScan
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
@EnableAutoConfiguration
: enable Spring Boot’s auto-configuration mechanism@ComponentScan
: enable@Component
scan on the package where the application is located (see the best practices)@Configuration
: allow to register extra beans in the context or import additional configuration classes
The user-defined beans are imported explicitly, these beans are not in package defined in
@ComponentScan with arguments or even no annotation @ComponentScan
@Import({ MyConfig.class, MyAnotherConfig.class })
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<mainClass>com.iot.gateway.admin.Application</mainClass>
</configuration>
</plugin>
</plugins>
</build>
<repositories> <repository> <id>nexus-aliyun</id> <name>Nexus aliyun</name> <url>http://maven.aliyun.com/nexus/content/groups/public</url> </repository> </repositories>
<dependencyManagement> <dependencies> <!-- Override Spring Data release train provided by Spring Boot --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-releasetrain</artifactId> <version>Fowler-SR2</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.1.0.BUILD-SNAPSHOT</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
SpringApplication.setRegisterShutdownHook(false)
The spring-boot-devtools
module can be included in any project to provide additional development-time features
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies>
System.setProperty("spring.devtools.restart.enabled", "false");
Output debug information
$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug
Accessing Application Arguments
@Component public class MyBean { @Autowired public MyBean(ApplicationArguments args) { boolean debug = args.containsOption("debug"); List<String> files = args.getNonOptionArgs(); // if run with "--debug logfile.txt" debug=true, files=["logfile.txt"] } }
Spring Boot also registers a CommandLinePropertySource
with the Spring Environment
. This lets you also inject single application arguments by using the @Value
annotation.
Using the ApplicationRunner or CommandLineRunner
@Component public class MyBean implements CommandLineRunner { public void run(String... args) { // Do something... } }
Application Exit
Each SpringApplication
registers a shutdown hook with the JVM to ensure that the ApplicationContext
closes gracefully on exit.
All the standard Spring lifecycle callbacks (such as the DisposableBean
interface or the @PreDestroy
annotation) can be used.
Externalized Configuration/Application Property Files
file:./custom-config/
classpath:custom-config/
file:./config/
file:./
classpath:/config/
classpath:/
Profile-specific Properties
application-{profile}.properties
spring.profiles.active
Define the context path
server:
context-path: /web
DruidDataSourceAutoConfigure
@Configuration @ConditionalOnClass(com.alibaba.druid.pool.DruidDataSource.class) @AutoConfigureBefore(DataSourceAutoConfiguration.class) @EnableConfigurationProperties({DruidStatProperties.class, DataSourceProperties.class}) @Import({DruidSpringAopConfiguration.class, DruidStatViewServletConfiguration.class, DruidWebStatFilterConfiguration.class, DruidFilterConfiguration.class})
@ConditionalOnProperty("spring.datasource.druid.aop-patterns") // @Value("${spring.aop.proxy-target-class:false}") // @Bean @ConfigurationProperties(FILTER_STAT_PREFIX) @ConditionalOnProperty(prefix = FILTER_STAT_PREFIX, name = "enabled", matchIfMissing = true) @ConditionalOnMissingBean public StatFilter statFilter() { return new StatFilter(); } // @ConditionalOnWebApplication @ConditionalOnProperty(name = "spring.datasource.druid.stat-view-servlet.enabled", havingValue = "true", matchIfMissing = true) // @Configuration @ConditionalOnClass(com.alibaba.druid.pool.DruidDataSource.class) @AutoConfigureBefore(DataSourceAutoConfiguration.class) @EnableConfigurationProperties({DruidStatProperties.class, DataSourceProperties.class}) @Import({DruidSpringAopConfiguration.class, DruidStatViewServletConfiguration.class, DruidWebStatFilterConfiguration.class, DruidFilterConfiguration.class})
@org.springframework.context.annotation.Configuration @ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class }) @ConditionalOnBean(DataSource.class) @EnableConfigurationProperties(MybatisProperties.class) @AutoConfigureAfter(DataSourceAutoConfiguration.class)
@NestedConfigurationProperty
Use SpringBean in Filter
@Override public void init(FilterConfig filterConfig) throws ServletException { SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, filterConfig.getServletContext()); }
ServletContext servletContext = filterConfig.getServletContext(); WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext); tokenService = wac.getBean(TokenService.class);
Multi-Datasource and Multi-JdbcTemplate
@Configuration public class DataSourceConfig { @Primary @Bean(name = "mysqldatasource") @ConfigurationProperties("spring.datasource.druid.mysql") public DataSource dataSourceOne(){ return DruidDataSourceBuilder.create().build(); } @Bean(name = "oracledatasource") @ConfigurationProperties("spring.datasource.druid.oracle") public DataSource dataSourceTwo(){ return DruidDataSourceBuilder.create().build(); } @Bean(name = "mysqlJdbcTemplate") public JdbcTemplate primaryJdbcTemplate(@Qualifier("mysqldatasource") DataSource dataSource) { return new JdbcTemplate(dataSource); } @Bean(name = "oracleJdbcTemplate") public JdbcTemplate secondaryJdbcTemplate(@Qualifier("oracledatasource") DataSource dataSource) { return new JdbcTemplate(dataSource); } } @Repository public class MysqlStudentDaoImp implements MysqlStudentDao{ @Autowired @Qualifier("mysqlJdbcTemplate") private JdbcTemplate jdbcTemplate; @Override public List<Map<String, Object>> getAllStudents() { return this.jdbcTemplate.queryForList("select * from student"); } }
Spring Import Beans
// @Import({User.class,Role.class}) // @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @PropertySource("classpath:/wx.properties") @EnableConfigurationProperties(WxProperties.class) @Import({WxInvokerConfiguration.class, WxAsyncMessageConfiguration.class, WxBuildinMvcConfiguration.class, WxTokenConfiguration.class, WxMediaConfiguration.class, WxWebConfiguration.class}) public @interface EnableWxMvc{ } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootApplication @EnableWxMvc public @interface WxApplication { } // public class MyConfig { @Bean public Runnable createRunnble1() { return () -> {}; } } @Import({MyConfig .class}) // @Import({MyImportSelector.class,MyImportBeanDefinitionRegistrar }) public class MyImportSelector implements ImportSelector{ @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { //可以获取到注解信息,然后根据注解信息动态的返回被spring容器托管的bean System.out.println(importingClassMetadata.getAnnotationAttributes(EnableLog.class.getName())); return new String[] User.class.getName(),Role.class.getName(),MyConfig.class.getName()}; } } public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar{ }
HttpMessageConverter