Java中核心注解的作用及其使用,了解Spring容器装载的过程和机制,自定义注解来实现自动配置项目依赖环境,包括mybatis、Dubbo、log4j、RabbitMQ、redis相关等自动配置。
springboot 核心注解
主要注解有:
@SpringBootApplication
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
@Configuration
@Component
@Indexed
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
@Repeatable(ComponentScans.class)
@AutoConfigureAfter,
@AutoConfigureBefore,
@AutoConfigureOrder,
@Bean(destroyMethod = "close")
@DependsOn({"loadConfiguration"})
@ConditionalOnMissingBean //当容器里没有指定的Bean的情况下创建该对象
@Controller
@Autowired
@Service
@ResponseBody
@RestController
@RequestMapping("/book")
@Mapping
自定义接注解
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
@ComponentScan(basePackages = {"com.ycj.fastframe.springconfig"})
@Inherited
public @interface AutoLoadConfiguration {
}
springboot 扫描顺序
1.1 springboot启动会扫描一下classpath:位置的application.properties或者application.yml作为默认的配置文件,之后依次从下面的位置开始扫描。
工程根目录:./config/
工程根目录:./
classpath:/config/
classpath:/
加载的优先级顺序是从上向下加载,并且所有的文件都会被加载,高优先级的内容会覆盖底优先级的内容,形成互补配置。
也可以通过指定配置spring.config.location来改变默认配置,一般在项目已经打包后,可以通过指令
java -jar xxxx.jar --spring.config.location=D:/kawa/application.yml
来加载外部的配置。
关于Resource接口
在使用spring作为容器进行项目开发中会有很多的配置文件,这些配置文件都是通过Spring的Resource接口来实现加载,其实Spring的Resource接口是对java.net.URL的一个强化,因为我们的配置文件不仅仅是来自于http请求或者ftp请求,还有很多classpath或者fileSystem或者InputStream(很少见),为了解决这个需求Spring开发了Resource接口:
Resource只是一个标准,一个用于解决上面说到的需求的标准,具体的使用方式有以下几种:
1.引用http资源
2.引用classpath资源
3.引用fileSystem资源
4.使用相对路径的资源
使用示例:
ClassPathXmlApplicationContext cx = new ClassPathXmlApplicationContext();
//http:
Resource template1 = cx.getResource("http://www.baidu.com");
//classpath:
Resource template2 = cx.getResource("classpath:application.properties");
//fileSystem:
Resource template3 = cx.getResource("file:D:/spring-aop-3.1.xsd");
//相对路径:必须和当前的ApplicationContext路径在一起
Resource template4 = cx.getResource("/test/Messenger.groovy");
使用自定义注解自动配置
详细使用如下: