目录
1、Springboot的核心注解 @SpringBootApplication
7、@EnableConfigurationProperties
1、Springboot的核心注解 @SpringBootApplication
@SpringBootApplication包含了三个注解及其含义: @SpringBootConfiguration,@EnableAutoConfiguration,@ComponentScan
- @SpringBootConfiguration 在这个类的源码中还有一个@Configuration的注解,@Configuration注解的作用就是声明当前类为配置类,然后Spring会自动扫描到添加了@Configuration的类,读取其中的配置信息,而@SpringBootConfiguration是用来声明当前类是SpringBoot应用的配置类,项目中只能有一个。
- @EnableAutoConfiguration 开启自动配置,告诉SpringBoot基于所添加的依赖,去“猜测”你要如何配置Spring,比如我们引入了spring-boot-starter-web,而这个启动器中帮我们添加了tomcat,SpringMVC的依赖,因此自动配置就知道你是要开发一个web应用,所以就帮你完成了web以及SpringMVC的默认配置了。我们使用SpringBoot构建一个项目,只需要引入所需要的框架的依赖,配置就可以交给SpringBoot处理了。
- @ComponentScan 配置组件扫描指令,通过basePackageClasses或者basePackages属性来指定要扫描的包。如果没有指该属性,那么将从声明这个注释的类的所在包及其子包开始扫描。
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class, scanBasePackages = { "com.oc2", "com.equery.endpoint.filter", "com.equery.endpoint.facade", "com.equery.config", "com.equery.facade", "com.equery.biz" })
/* * Copyright 2012-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.context.TypeExcludeFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.core.annotation.AliasFor; /** * Indicates a {@link Configuration configuration} class that declares one or more * {@link Bean @Bean} methods and also triggers {@link EnableAutoConfiguration * auto-configuration} and {@link ComponentScan component scanning}. This is a convenience * annotation that is equivalent to declaring {@code @Configuration}, * {@code @EnableAutoConfiguration} and {@code @ComponentScan}. * * @author Phillip Webb * @author Stephane Nicoll * @since 1.2.0 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class)) public @interface SpringBootApplication { /** * Exclude specific auto-configuration classes such that they will never be applied. * @return the classes to exclude */ Class<?>[] exclude() default {}; /** * Exclude specific auto-configuration class names such that they will never be * applied. * @return the class names to exclude * @since 1.3.0 */ String[] excludeName() default {}; /** * Base packages to scan for annotated components. Use {@link #scanBasePackageClasses} * for a type-safe alternative to String-based package names. * @return base packages to scan * @since 1.3.0 */ @AliasFor(annotation = ComponentScan.class, attribute = "basePackages") String[] scanBasePackages() default {}; /** * Type-safe alternative to {@link #scanBasePackages} for specifying the packages to * scan for annotated components. The package of each class specified will be scanned. * <p> * Consider creating a special no-op marker class or interface in each package that * serves no purpose other than being referenced by this attribute. * @return base packages to scan * @since 1.3.0 */ @AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses") Class<?>[] scanBasePackageClasses() default {}; }
2、将类注释为一个组件托管在容器中
-
@Repository 用于标注数据访问组件
-
@Controller 用于标注控制层组件
-
@Service 用于标注业务层
-
@Component("giftOrEliteProcessor") 泛指组件,用于不好分类的时候
-
@Bean 放在方法上 用于告诉方法,产生一个bean对象(可以注册组件的方法的返回类型必须是引用类型)
// 例如多数据源中建立数据源的方法 @Configuration @Order(Integer.MIN_VALUE) public class DataSourceAutoConfig { @Autowired private Environment environment; @Primary @Bean(name = "paDataSource") public DataSource paDataSource() throws Exception{ String dsName = "pa"; return createByName(dsName); } @Bean(name = "nb2DataSource") public DataSource nb2DataSource() throws Exception{ String dsName = "nb2"; return createByName(dsName); } private DataSource createByName(String dsName) throws Exception{ Properties properties = new Properties(); for(Map.Entry<String, String> entry : DruidDataSourceProperties.getPropertiesKeys().entrySet()){ StringBuilder buffer = new StringBuilder(dsName); String dsConfigKey = buffer.append(entry.getValue()).toString(); properties.put(entry.getKey(),environment.getProperty(dsConfigKey)); } return DruidDataSourceFactory.createDataSource(properties); } @Bean(name = "paTransactionManager") public DataSourceTransactionManager paTransactionManager() throws Exception{ return new DataSourceTransactionManager(paDataSource()); } @Bean(name = "nb2TransactionManager") public DataSourceTransactionManager nbTransactionManager() throws Exception{ return new DataSourceTransactionManager(nb2DataSource()); } }
3、@ImportResource 和 @Import
- @ImportResource 用来加载指定路径下的xml配置
- @Import 用来导入其他配置类
@ImportResource({"classpath*:META-INF/cpp/core-service.xml"}) // 用来加载指定路径下的xml配置
@Import({CppUtilConfig.class}) // 用来导入其他配置类
4、@Value("${redis.port}")
用于通过 application.properties 文件中的配置来配置属性的值。
@Value("${redis.host}")
private String host;
5、@AutoWired 装配bean
默认使用byType的方式进行注入,将配置好的bean拿来用,完成属性,方法的组装,他可以对类成员变量,方法及构造函数进行标注,完成自动装配工作。
如果增加(required == false)时,就算找不到对应的bean也不会报错。
@Autowired
@Qualifier("oc2ThreadPool")
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
6、@Resource 装配bean
默认使用byName的方式进行注入,@Resource有两个比较重要的属性:byName或者byType
@Resource装配的顺序:
- 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常。
- 如果指定了name,则从上下文中查找名称id匹配的bean进行装配,找不到则抛出异常。
- 如果指定了type,则从上下文中查找类型匹配的唯一bean进行装配,找不到或者找到多个都会抛出异常。
- 如果既没有指定name也没有指定type,则自动按照byName的形式进行装配,如果没有匹配,则回退为一个原始类型进行匹配。
面试相关问题:@AutoWired和@Resource的区别是什么?
- @Autowired 默认用byType的方式注入bean,@Resource默认适应byName的方式注入bean
- @AutoWired是Spring的注解,@Resource是J2EE的注解是Java自己的东西,使用@Resource可以减少代码和Spring的耦合。
7、@EnableConfigurationProperties
该注解的作用是 : 让 使用了 @ConfigurationProperties 注解的类生效。
如果一个配置类只配置@ConfigurationProperties注解,而没有使用@Component,那么在IOC容器中是获取不到properties 配置文件转化的bean。说白了 @EnableConfigurationProperties 相当于把使用 @ConfigurationProperties 的类进行了一次注入。
@ConfigurationProperties(prefix = "async.db")
public class AsyncSharedItemThreadProperteis {
private int corePoolSize = 10;
private int maxPoolSize = 10;
private int queue = 1024;
private int keepAliveSeconds = 60;
private String threadNamePrefix = "AsyncSharedItemExecutor-";
// ------- 各种配置数据值
}
// ------------------------------------------------------------------------
@Configuration
@EnableConfigurationProperties(value = AsyncSharedItemThreadProperteis.class)
public class AnsySharedItemThreadConfig {
@Autowired
AsyncSharedItemThreadProperteis asyncSharedItemThreadProperteis;
public Executor sharedItemThreadPool(){
MdcThreadPoolTaskExecutor executor = new MdcThreadPoolTaskExecutor();
executor.setCorePoolSize(asyncSharedItemThreadProperteis.getCorePoolSize());
// ---------
}