Spring注解开发系列(一)

统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop、事物,这么做有两个缺点:
1、如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大;如果按需求分开.xml文件,那么.xml文件又会非常多。总之这将导致配置文件的可读性与可维护性变得很低。
2、在开发中在.java文件和.xml文件之间不断切换,是一件麻烦的事,同时这种思维上的不连贯也会降低开发的效率。
为了解决这两个问题,Spring引入了注解,通过"@XXX"的方式,让注解与Java Bean紧密结合,既大大减少了配置文件的体积,又增加了Java Bean的可读性与内聚性。

1.@Configuration&@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);
    }
}

2.@ComponentScan-自动扫描组件&指定扫描规则

该注解会自动扫描包路径下面的所有@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让默认的过滤器失效

猜你喜欢

转载自www.cnblogs.com/wangxiayun/p/10083217.html