記錄一些spring Boot中的注解,一方面幫助記憶,一方面用的時候可以查詢.
**@Controller **
@Controller 用于標記在一個類上,使用它標記的類就是一個SpringMVC Controller 對象。分發處理器將會掃描使用了該注解的類的方法,并檢測該方法是否使用了@RequestMapping 注解。@Controller 只是定義了一個控制器類,而使用@RequestMapping 注解的方法才是真正處理請求的處理器。
@RestController
@RestController注解相當于@ResponseBody + @Controller合在一起的作用。
@RequestBody
將HTTP請求正文轉換為適合的HttpMessageConverter對象。
@ResponseBody
將內容或對象作為 HTTP 響應正文返回,并調用適合HttpMessageConverter的Adapter轉換對象,寫入輸出流。
@Value
通過@Value("對應name"),獲取到.properties配置內容。
@ConfigurationProperties
使用上面的@Value注解,如果內容多的話太麻煩.可以把.properties改為yml格式.在bean中使用@ConfigurationProperties(prefix = "com.lrj")自動加載.
d
自動注解,@Autowired可以對成員變量、方法和構造函數進行標注,來完成自動裝配的工作。
@RequestMapping
@RequestMapping 用來映射URL 到控制器類,或者是到Controller 控制器的處理方法上。比如在@Controller下聲明@RequestMapping那么在調用這個控制類
的時候需要加上對應的映射名,在方法上聲明一樣.
method屬性用于聲明調用方法的方式.如:method = RequestMethod.GET,RequestMethod.POST。
@SpringBootApplication
@SpringBootApplication = (默認屬性)@Configuration + @EnableAutoConfiguration + @ComponentScan。
下面分別寫下三個對應注解的功能。
@Configuration
@Configuration的注解類標識這個類可以使用Spring IoC容器作為bean定義的來源。@Bean注解告訴Spring,一個帶有@Bean的注解方法將返回一個對象,該
對象應該被注冊為在Spring應用程序上下文中的bean。
@Configuration和在xml中配置的區別:
基于XML配置的方式是這樣:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" default-lazy-init="true">
<bean id="mockService" class="..MockServiceImpl"> <propery name ="dependencyService" ref="dependencyService" /></bean><bean id="dependencyService" class="DependencyServiceImpl"></bean>
</beans>
基礎@Configuration注解的代碼是這樣:
@Configurationpublic class MockConfiguration{ @Bean public MockService mockService(){ return new MockServiceImpl(dependencyService()); } @Bean public DependencyService dependencyService(){ return new DependencyServiceImpl(); }}
@ComponentScan
****@component (把普通pojo實例化到spring容器(IOC)中,相當于配置文件中的<bean id="" class=""/>)
@Component,@Service,@Controller,@Repository注解的類,并把這些類納入進spring容器(IOC)中管理。
下面寫這個是引入component的掃描組件 <context:component-scan base-package=”com.mmnc”> 其中base-package為需要掃描的包(含所有子包) 1、@Service用于標注業務層組件 2、@Controller用于標注控制層組件(如struts中的action) 3、@Repository用于標注數據訪問組件,即DAO組件. 4、@Component泛指組件,當組件不好歸類的時候,我們可以使用這個注解進行標注。 @Service public class UserServiceImpl implements UserService { } @Repository public class UserDaoImpl implements UserDao { } getBean的默認名稱是類名(頭字母小寫),如果想自定義,
可以@Service(“***”)這樣來指定,這種bean默認是單例的,如果想改變,可以使用@Service(“beanName”) @Scope(“prototype”)來改變。可以使用以下方式指定初始化方法和銷毀方法(方法名任意):
@PostConstruct public void init() { }
**@EnableAutoConfiguration **
@EnableAutoConfiguration能夠自動配置spring的上下文,試圖猜測和配置你想要的bean類,通常會自動根據你的類路徑和你的bean定義自動配置。
@Autowired
自動注解,@Autowired可以對成員變量、方法和構造函數進行標注,來完成自動裝配的工作。