什么是基于Java的Spring注解配置? 給一些注解的例子.
- 基于Java的配置器钟,允許你在少量的Java注解的幫助下锯茄,進(jìn)行你的大部分Spring配置而非通過(guò)XML文件宫仗。
- 以@Configuration 注解為例,它用來(lái)標(biāo)記類可以當(dāng)做一個(gè)bean的定義,被Spring IOC容器使用梳杏。另一個(gè)例子是@Bean注解,它表示此方法將要返回一個(gè)對(duì)象,作為一個(gè)bean注冊(cè)進(jìn)Spring應(yīng)用上下文拍鲤。
怎樣開(kāi)啟注解裝配?
注解裝配在默認(rèn)情況下是不開(kāi)啟的汞扎,為了使用注解裝配季稳,我們必須在Spring配置文件中配置 <context:annotation-config/>元素。
解釋@Required注解
- 這個(gè)注解表明bean的屬性必須在配置的時(shí)候設(shè)置
- 若@Required注解的bean屬性未被設(shè)置澈魄,容器將拋出BeanInitializationException景鼠。
public class EmployeeFactoryBean extends AbstractFactoryBean<Object>
{
private String designation;
public String getDesignation() {
return designation;
}
@Required
public void setDesignation(String designation) {
this.designation = designation;
}
//more code here
}
RequiredAnnotationBeanPostProcessor是Spring中的后置處理用來(lái)驗(yàn)證被@Required 注解的bean屬性是否被正確的設(shè)置了。
在使用RequiredAnnotationBeanPostProcesso來(lái)驗(yàn)證bean屬性之前,首先要在IoC容器中對(duì)其進(jìn)行注冊(cè):
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />
解釋@Autowired注解
- @Autowired注解對(duì)自動(dòng)裝配何時(shí)何處被實(shí)現(xiàn)提供了更多細(xì)粒度的控制铛漓。
- @Autowired注解可以像@Required注解溯香、構(gòu)造器一樣被用于在bean的設(shè)值方法上自動(dòng)裝配bean的屬性,一個(gè)參數(shù)或者帶有任意名稱或帶有多個(gè)參數(shù)的方法浓恶。
- 比如玫坛,可以在設(shè)值方法上使用@Autowired注解來(lái)替代配置文件中的元素。
當(dāng)Spring容器在setter方法上找到@Autowired注解時(shí)包晰,會(huì)嘗試用byType 自動(dòng)裝配湿镀。 - 當(dāng)然我們也可以在構(gòu)造方法上使用@Autowired 注解。帶有@Autowired 注解的構(gòu)造方法意味著在創(chuàng)建一個(gè)bean時(shí)將會(huì)被自動(dòng)裝配伐憾,即便在配置文件中使用元素勉痴。
public class TextEditor {
private SpellChecker spellChecker;
@Autowired
public TextEditor(SpellChecker spellChecker){
System.out.println("Inside TextEditor constructor." );
this.spellChecker = spellChecker;
}
public void spellCheck(){
spellChecker.checkSpelling();
}
}
下面是沒(méi)有構(gòu)造參數(shù)的配置方式:
<beans>
<context:annotation-config/>
<!-- Definition for textEditor bean without constructor-arg -->
<bean id="textEditor" class="com.howtodoinjava.TextEditor">
</bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.howtodoinjava.SpellChecker">
</bean>
</beans>
說(shuō)明@Qualifier注解
- 當(dāng)有多個(gè)相同類型的bean卻只有一個(gè)需要自動(dòng)裝配時(shí),將@Qualifier 注解和@Autowire 注解結(jié)合使用以消除這種混淆树肃,指定需要裝配的確切的bean蚀腿。
下面的示例將會(huì)在Customer的person屬性中自動(dòng)裝配person的值。
public class Customer
{
@Autowired
private Person person;
}
下面我們要在配置文件中來(lái)配置Person類扫外。
<bean id="customer" class="com.howtodoinjava.common.Customer" />
<bean id="personA" class="com.howtodoinjava.common.Person" >
<property name="name" value="lokesh" />
</bean>
<bean id="personB" class="com.howtodoinjava.common.Person" >
<property name="name" value="alex" />
</bean>
Spring會(huì)知道要自動(dòng)裝配哪個(gè)person bean么?不會(huì)的莉钙,但是運(yùn)行上面的示例時(shí),會(huì)拋出下面的異常:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type [com.howtodoinjava.common.Person] is defined:
expected single matching bean but found 2: [personA, personB]
要解決上面的問(wèn)題筛谚,需要使用 @Quanlifier注解來(lái)告訴Spring容器要裝配哪個(gè)bean:
public class Customer
{
@Autowired
@Qualifier("personA")
private Person person;
}
一些注解
@Service用于標(biāo)注業(yè)務(wù)層組件
@Controller用于標(biāo)注控制層組件(如struts中的action)
@Repository用于標(biāo)注數(shù)據(jù)訪問(wèn)組件磁玉,即DAO組件
@Component泛指組件,當(dāng)組件不好歸類的時(shí)候驾讲,我們可以使用這個(gè)注解進(jìn)行標(biāo)注蚊伞。
component-scan標(biāo)簽
component-scan標(biāo)簽?zāi)J(rèn)情況下自動(dòng)掃描指定路徑下的包(含所有子包),將帶有@Component吮铭、@Repository时迫、@Service、@Controller標(biāo)簽的類自動(dòng)注冊(cè)到spring容器谓晌。對(duì)標(biāo)記了 Spring's @Required掠拳、@Autowired、JSR250's @PostConstruct纸肉、@PreDestroy溺欧、@Resource、JAX-WS's @WebServiceRef柏肪、EJB3's @EJB姐刁、JPA's @PersistenceContext、@PersistenceUnit等注解的類進(jìn)行對(duì)應(yīng)的操作使注解生效(包含了annotation-config標(biāo)簽的作用)
注解大全
Spring項(xiàng)目中會(huì)用到大量的注解烦味,這里羅列以下常用的聂使。除過(guò)這些外SpringBoot、SpringSecurity、SpringData等也有大量的注解
原地址:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/package-summary.html
(1)Context org.springframework.context.annotation
@Configuration
@ComponentScan
@ComponentScans
@Conditional
@Bean
@Lazy
@DependsOn
@Import
@ImportResource
@Primary
@Profile
@Scope
@Description
@PropertySource
@PropertySources
@Role
(2)Bean org.springframework.beans.factory.annotation
@Autowired
@Qualifier
@Required
@Scope
@Lookup
@Value
@Configurable
(3)Core org.springframework.core.annotation
@Order
@AliasFor
(4)Stereotyping org.springframework.stereotype
@Component
@Controller
@Service
@Repository
(5)Web org.springframework.web.bind.annotation
@Controller
@ControllerAdvice
@InitBinder
@ModelAttribute
@MatrixVariable
@RequestMapping
@RequestParam
@RequestPart
@RequestBody
@RequestHeader
@RequestAttribute
@SessionAttribute
@SessionAttributes
@CookieValue
@ExceptionHandler
@CrossOrigin
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
@RestController
@RestControllerAdvice
@ResponseBody
@ResponseStatus
@PathVariable
(6)Transaction org.springframework.transaction.annotation
@EnableTransactionManagement
@Transactional
(7)Cache org.springframework.cache.annotation
@EnableCaching
@CacheConfig
@Cacheable
@Caching
@CachePut
@CacheEvict
(8)Schedule org.springframework.scheduling.annotation
@EnableAsync
@Async
@EnableScheduling
@Scheduled
@Schedules
(9)Aspect org.aspectj.lang.annotation
@Aspect
@After
@AfterReturning
@AfterThrowing
@Around
@Before
@DeclareParents
@Pointcut
(10)JSR-250 javax.annotation
@PostConstruct
@PreDestroy
@Resource
(11)JSR-330 javax.inject
@Inject
@Named
(12)JSR-303 javax.validation.constraints
@Max
@Min
@NotNull
@Size
@Pattern
@Valid
Hibernate Validator org.hibernate.validator.constraints
@Email
@Length
@Digits
@NotEmpty
@NotBlank
@Range
@URL
@Past
@Future
(13)MyBatis org.apache.ibatis.annotations
@Param
@Select
@Update
@Delete
@Insert
@Results
@Result
@Options
(14)其他
@EnableWebMvc org.springframework.web.servlet.config.annotation
@Validated org.springframework.validation.annotation
@MapperScan org.mybatis.spring.annotation
@Alias org.apache.ibatis.type.Alias