聲明bean的注解:
@Component組件,沒有明確角色的bean
@Service,在業務邏輯層(service)中使用
@Repository,在數據訪問層(dao)中使用
@Controller,在展現層中使用
@Configuration聲明配置類
實體類無需添加注解,因為并不需要“注入”實體類
指定Bean的作用域的注解:
@Scope("prototype")
默認值為singleton
可選值prototype、request、session、globalSession
聲明生成Bean的方法的注解:
@Bean 用在方法上,告訴Spring容器,你可以從下面這個方法中拿到一個Bean
使用AnnotationApplicationContext對象的getBean方法獲取Bean
注入Bean的注解:
@Autowired,自動注入(默認為byType型的注入),可以用在屬性或者方法上,可以通過設置required = "false"說明不要求一定要注入有多個同樣的接口的實現時,通過@qualifier區分
當注入的變量為List后者Map時,會把所有的接口實現都注入進來,key為Bean的名字,value為實現類對象。可以通過在實現類上添加@order=1來指定加載順序,數越小越優先加載
@Lazy啟動延遲注入
配置類注解:
@Configuration聲明當前類是一個配置類,相當于Spring配置的一個xml文件
@ComponentScan,自動掃描配置類所在包名下的所有bean
@EnableAutoConfiguration,啟動自動配置
在spring boot中這三個注解可以用一個@SpringBootApplication替代
@EnableTransactionManagement,開啟事務支持
事務管理:
@EnableTransactionManagement,加在配置類中,開啟事務支持
@Transactional,加在Service的方法上,標注需要事務支持
AOP注解:
@AspectJ
任務調度:
1
2
|
@Scheduled 用在需要定時執行的方法上 @EnableScheduling 用在需要使用的入口類上 |
Spring MVC集成:
首先需要對Application類進行修改
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
@SpringBootApplication @EnableTransactionManagement //1、添加繼承SpringBootServletInitializer public class Application extends SpringBootServletInitializer{ public static void main(String[] args) { SpringApplication.run(Application. class , args); } @Override //2、重寫configure方法 protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return super .configure(builder); } } Spring MVC的注解: @Controller ,在展現層使用 @ResponseBody @RestController |
以上所述是小編給大家介紹的Spring Boot注解學習(一),希望對大家有所幫助!