SpringBoot經常使用註解整理

@SpringBootApplication 定義在main方法入口類處,用於啓動sping boot應用項目java

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Configuration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication {

	/** * Exclude specific auto-configuration classes such that they will never be applied. * @return the classes to exclude */
	Class<?>[] exclude() default {};

}
複製代碼

@EnableAutoConfiguration 讓spring boot根據類路徑中的jar包依賴當前項目進行自動配置 在src/main/resources的META-INF/spring.factoriesweb

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration
如有多個自動配置,用「,」隔開
複製代碼

@ImportResource 加載XML文件,通常是放在啓動main類上spring

@ImportResource("classpath*:/spring/*.xml")  單個
@ImportResource({"classpath*:/spring/1.xml","classpath*:/spring/2.xml"})   多個
複製代碼

@Value application.properties定義屬性,直接使用@Value注入便可json

public class A{
	 @Value("${push.start:0}")    若是缺失,默認值爲0
     private Long  id;
}
複製代碼

@ConfigurationProperties(prefix="person") 能夠新建一個properties文件,ConfigurationProperties的屬性prefix指定properties的配置的前綴,經過location指定properties文件的位置api

@ConfigurationProperties(prefix="person")
public class PersonProperties {
	
	private String name ;
	private int age;
}
複製代碼

@EnableConfigurationProperties 用 @EnableConfigurationProperties註解使 @ConfigurationProperties生效,並從IOC容器中獲取bean 博客地址:blog.csdn.net/u010502101/… @RestController 組合@Controller和@ResponseBody,當你開發一個和頁面交互數據的控制時,好比bbs-web的api接口須要此註解 @RequestMapping("/api2/copper") 用來映射web請求(訪問路徑和參數)、處理類和方法,能夠註解在類或方法上。註解在方法上的路徑會繼承註解在類上的路徑。 produces屬性: 定製返回的response的媒體類型和字符集,或需返回值是json對象markdown

@RequestMapping(value="/api2/copper",produces="application/json;charset=UTF-8",method = RequestMethod.POST)
複製代碼

@RequestParam 獲取request請求的參數值app

public List<CopperVO> getOpList(HttpServletRequest request, @RequestParam(value = "pageIndex", required = false) Integer pageIndex, @RequestParam(value = "pageSize", required = false) Integer pageSize) {
 
  }
複製代碼

@ResponseBody 支持將返回值放在response體內,而不是返回一個頁面。好比Ajax接口,能夠用此註解返回數據而不是頁面。此註解能夠放置在返回值前或方法前。微服務

另外一個玩法,能夠不用@ResponseBody。
繼承FastJsonHttpMessageConverter類並對writeInternal方法擴展,在spring響應結果時,再次攔截、加工結果
// stringResult: json返回結果
//HttpOutputMessage outputMessage

 byte[] payload = stringResult.getBytes();
 outputMessage.getHeaders().setContentType(META_TYPE);
 outputMessage.getHeaders().setContentLength(payload.length);
 outputMessage.getBody().write(payload);
 outputMessage.getBody().flush();
複製代碼

@Bean @Bean(name="bean的名字",initMethod="初始化時調用方法名字",destroyMethod="close") 定義在方法上,在容器內初始化一個bean實例類oop

@Bean(destroyMethod="close")
@ConditionalOnMissingBean
public PersonService registryService() {
		return new PersonService();
	}
複製代碼

@Service 用於標註業務層組件 @Controller 用於標註控制層組件(如struts中的action) @Repository 用於標註數據訪問組件,即DAO組件 @Component 泛指組件,當組件很差歸類的時候,咱們可使用這個註解進行標註。 @PostConstruct spring容器初始化時,要執行該方法ui

@PostConstruct  
public void init() {   
}   
複製代碼

@PathVariable 用來得到請求url中的動態參數

@Controller  
public class TestController {  

     @RequestMapping(value="/user/{userId}/roles/{roleId}",method = RequestMethod.GET)  
     public String getLogin(@PathVariable("userId") String userId, @PathVariable("roleId") String roleId){
           
         System.out.println("User Id : " + userId);  
         System.out.println("Role Id : " + roleId);  
         return "hello";  
     
     }  
}
複製代碼

@ComponentScan 註解會告知Spring掃描指定的包來初始化Spring

@ComponentScan(basePackages = "com.bbs.xx")
複製代碼

@EnableZuulProxy 路由網關的主要目的是爲了讓全部的微服務對外只有一個接口,咱們只需訪問一個網關地址,便可由網關將全部的請求代理到不一樣的服務中。Spring Cloud是經過Zuul來實現的,支持自動路由映射到在Eureka Server上註冊的服務。Spring Cloud提供了註解@EnableZuulProxy來啓用路由代理 @Autowired 在默認狀況下使用 @Autowired 註釋進行自動注入時,Spring 容器中匹配的候選 Bean 數目必須有且僅有一個。當找不到一個匹配的 Bean 時,Spring 容器將拋出 BeanCreationException 異常,並指出必須至少擁有一個匹配的 Bean 當不能肯定 Spring 容器中必定擁有某個類的 Bean 時,能夠在須要自動注入該類 Bean 的地方可使用 @Autowired(required = false),這等於告訴 Spring: 在找不到匹配 Bean 時也不報錯 @Autowired註解注入map、list與@Qualifier 博客地址:blog.csdn.net/ethunsex/ar… @Configuration

@Configuration("name")//表示這是一個配置信息類,能夠給這個配置類也起一個名稱
@ComponentScan("spring4")//相似於xml中的<context:component-scan base-package="spring4"/>
public class Config {

    @Autowired//自動注入,若是容器中有多個符合的bean時,須要進一步明確
    @Qualifier("compent")//進一步指明注入bean名稱爲compent的bean
    private Compent compent;

    @Bean//相似於xml中的<bean id="newbean" class="spring4.Compent"/>
    public Compent newbean(){
        return new Compent();
    }   
}
複製代碼

@Import(Config1.class) 導入Config1配置類裏實例化的bean

@Configuration
public class CDConfig {

    @Bean   // 將SgtPeppers註冊爲 SpringContext中的bean
    public CompactDisc compactDisc() {
        return new CompactDisc();  // CompactDisc類型的
    }
}

@Configuration
@Import(CDConfig.class)  //導入CDConfig的配置
public class CDPlayerConfig {

    @Bean(name = "cDPlayer")
    public CDPlayer cdPlayer(CompactDisc compactDisc) {  
         // 這裏會注入CompactDisc類型的bean
         // 這裏注入的這個bean是CDConfig.class中的CompactDisc類型的那個bean
        return new CDPlayer(compactDisc);
    }
}
複製代碼

@Order @Order(1),值越小優先級超高,越先運行 @ConditionalOnExpression

@Configuration
@ConditionalOnExpression("${enabled:false}")
public class BigpipeConfiguration {
    @Bean
    public OrderMessageMonitor orderMessageMonitor(ConfigContext configContext) {
        return new OrderMessageMonitor(configContext);
    }
}
複製代碼

開關爲true的時候才實例化bean @ConditionalOnProperty 這個註解可以控制某個 @Configuration 是否生效。具體操做是經過其兩個屬性name以及havingValue來實現的,其中name用來從application.properties中讀取某個屬性值,若是該值爲空,則返回false;若是值不爲空,則將該值與havingValue指定的值進行比較,若是同樣則返回true;不然返回false。若是返回值爲false,則該configuration不生效;爲true則生效 博客地址:blog.csdn.net/dalangzhong… @ConditionalOnClass 該註解的參數對應的類必須存在,不然不解析該註解修飾的配置類

@Configuration
@ConditionalOnClass({Gson.class})
public class GsonAutoConfiguration {
    public GsonAutoConfiguration() {
    }

    @Bean
    @ConditionalOnMissingBean
    public Gson gson() {
        return new Gson();
    }
}
複製代碼

@ConditionalOnMisssingClass({ApplicationManager.class}) 若是存在它修飾的類的bean,則不須要再建立這個bean @ConditionOnMissingBean(name = "example") 表示若是name爲「example」的bean存在,該註解修飾的代碼塊不執行

相關文章
相關標籤/搜索