SpringBoot常用注解

1.聲明Bean的注解:

@Compent :泛指組件,當(dāng)組件不好歸類的時候,我們可以使用這個注解進行標(biāo)注。

@Service :用于標(biāo)注業(yè)務(wù)層組件

@Repository:用于標(biāo)注數(shù)據(jù)訪問組件,即DAO組件

@Controller:用于標(biāo)注控制層組件(如struts中的action)?

@Bean : 注解到方法上,表示方法返回一個Bean,全局配置使用Java配置,如數(shù)據(jù)庫配置,業(yè)務(wù)配置使用上述的幾個注解

2.注入Bean的注解:

@Autowired? ? 可以注解到set方法或?qū)傩陨?/p>

@Resource?? 沒有括號內(nèi)內(nèi)容的話,默認byName。與@Autowired干類似的事。

@Inject

3.基礎(chǔ)注解:

@CompentScan :掃描組件路徑

@Configuration:說明這個類是配置文件

@scope:用來聲明Bean的Scope,有singleton,prototype,session,request。默認

@PropertySource:讀取配置文件地址

@ConfigurationProperties(prefix)? 配置文件映射對象

@Value :作用于變量或方法上,將配置文件中的變量設(shè)置到該變量上


@Value("${data.user}")//注入配置文件中的變量privateString user;

@Value("1232323")//注入字符串privateString testStr;

@Value("#{systemProperties['os.name']}")//注入系統(tǒng)變量privateString osName;

@Value("classpath:com/test/aspect/test.txt")//注入文件privateResource resource;

@Value("http://www.baidu.com")//注入網(wǎng)站資源privateResource baidu;

@Value("#{service.other}")//注入其他組建的變量privateString other;


4.bean生命周期

@PostContruct? 在構(gòu)造器后執(zhí)行,相當(dāng)于 @Bean 的 initMethod

@PreDestroy : 在銷毀前執(zhí)行? ,相當(dāng)于@Bean的destroyMethod

5.profile

@Profile(value="") 為 在不同的環(huán)境中使用不同的配置提供了支持;例如數(shù)據(jù)庫的配置

@Profile("dev")//環(huán)境為dev時初始化這個Bean@BeanpublicServicedevService(){returnnewService();? ? }@Profile("test")@BeanpublicServicetestService(){returnnewService();? ? }

6.定時任務(wù)

@EnableScheduing 開啟定時任務(wù)支持

@Scheduled? 有三個參數(shù),corn? ,fixedDelay , fixedRate? 后面?zhèn)z個單位為毫秒

7.測試

@RunWith(SpringJUnit4ClassRunner.class)

@SpringBootTest(classes ={Application.class})

@ActiveProfiles("test")

8.SpringMvc

@requestBody:該注解常用來處理Content-Type: 不是application/x-www-form-urlencoded編碼的內(nèi)容,例如application/json, application/xml等;

@RequestHeader:獲取header中的值

@CookieValue:獲取cookie中的值

@Pathvariable :當(dāng)使用@RequestMapping URI template 樣式映射時, 即 someUrl/{paramId}, 這時的paramId可通過 @Pathvariable注解綁定它傳過來的值到方法的參數(shù)上。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容