Spring註解開發系列(一)
阿新 • • 發佈:2018-12-07
傳統的Spring做法是使用.xml檔案來對bean進行注入或者是配置aop、事物,這麼做有兩個缺點:
1、如果所有的內容都配置在.xml檔案中,那麼.xml檔案將會十分龐大;如果按需求分開.xml檔案,那麼.xml檔案又會非常多。總之這將導致配置檔案的可讀性與可維護性變得很低。
2、在開發中在.java檔案和.xml檔案之間不斷切換,是一件麻煩的事,同時這種思維上的不連貫也會降低開發的效率。
為了解決這兩個問題,Spring引入了註解,通過"@XXX"的方式,讓註解與Java Bean緊密結合,既大大減少了配置檔案的體積,又增加了Java Bean的可讀性與內聚性。
[email protected] &@Bean給容器中註冊元件
@Configuration可理解為用spring的時候xml裡面的<beans>標籤
@Bean可理解為用spring的時候xml裡面的<bean>標籤
xml版:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--原始方式-->
<bean id="person" class="com.wang.bean.Person">
<property name="name" value="張三"></property>
<property name="age" value="18"></property>
</bean>
</beans>
註解版:
//在配置類裡配置 @Configuration//告訴spring這是一個配置類 public class PersonConfig { @Bean(value = "person") //給spring容器註冊一個bean,型別為返回值型別,id是預設是方法名為id,也可以使用value指定 public Person person(){ return new Person("lisi",20); } }
[email protected]自動掃描元件&指定掃描規則
該註解會自動掃描包路徑下面的所有@Controller、@Service、@Repository、@Component 的類
xml版:
<!--包掃描,只要註解了@Component,@Controller等會被掃描--> <context:component-scan base-package="com.wang" use-default-filters="false" > <!--排除某個註解,除了Controller其他類都會被掃描--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <!--只包含某個註解--> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
註解版:
@ComponentScan(value = "com.wang"/*excludeFilters = { //排除 @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class,Service.class}) //排除Controller和Service },*/,includeFilters = { //只包含 @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Repository.class}) },useDefaultFilters = false) //這裡要加useDefaultFilters=false讓預設的過濾器失效