雖然作業中交替會使用spring mvc 和spring boot 框架,但實際對spring中的很多注解并不是很了解,本篇將持續更新學習到的spring 注解,
Spring 主入口類上的注解
Spring boot專案中一般都會有這樣的啟動類:
@SpringBootApplication @ServletComponentScan(basePackages = { "com.xxx.web.controller" }) @ComponentScan(value = { "com.xxx" }) @EnableAutoConfiguration(exclude = { Xxx.class }) @EnableConfigurationProperties public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
那么,你對啟動類中的諸多注解了解多少?
@ServletComponentScan
在 SpringBootApplication 上使用@ServletComponentScan 注解后,Servlet、Filter、Listener 可以直接通過 @WebServlet、@WebFilter、@WebListener 注解自動注冊,無需其他代碼,
<style>p.p1 { margin: 0; font: 18px Monaco; color: rgba(119, 119, 119, 1) }</style>@ComponentScan
@ComponentScan告訴Spring哪個packages下用注解標識的類會被spring自動掃描并裝入bean容器,通俗一點說,如果你某個類用@Controller注解標識了,如果入口啟動類中不加上@ComponentScan注解,那么該Controller就不會被spring掃描到,更不會裝入Spring容易中,那么你在代碼中就不能使用@Autowired注解使用,換句話說,你配置的這個Controller便沒有意義,
@EnableAutoConfiguration
參考文章 鏈接,
從classpath中搜索所有META-INF/spring.factories組態檔,然后將其中org.springframework.boot.autoconfigure.EnableAutoConfiguration key對應的配置項加載到spring容器只有spring.boot.enableautoconfiguration為true(默認為true)的時候,才啟用自動配置
@EnableAutoConfiguration還可以進行排除,排除方式有2中,一是根據class來排除(exclude),二是根據class name(excludeName)來排除
其內部實作的關鍵點有
1)ImportSelector 該介面的方法的回傳值都會被納入到spring容器管理中
2)SpringFactoriesLoader 該類可以從classpath中搜索所有META-INF/spring.factories組態檔,并讀取配置
@EnableConfigurationProperties
讀取組態檔的資訊并自動封裝成物體類并在程式中直接使用,有一個物體類,物體類可以通過組態檔進行賦值,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/502286.html
標籤:Java
上一篇:3、spring+mybatis關聯映射(無mapper實作類)+idea+maven
下一篇:Java精進-手寫持久層框架
