spring 基于注解的配置

 

Fortunately, Spring offers a few tricks to help cut down on the amount of XML configuration required:

Spring 提供一些措施来帮助减少XML的配置量:

  • Autowiring:自动注入beans的属性
  • Autodiscovery:自动发现哪些类应该注册为bean

1.Automatically wiring bean properties

Spring支持4类自动装配的机制;同时也可以混用自动装配和显示的配置

  • byName
  • byType
  • constructor
  • autodetect

通过设置autowire="byName",来表明用哪种机制;既可以设置全局的autowire策略:default-autowire,也可以设置单个bean的策略:

  • <bean id="kenny" class="com.springinaction.springidol.Instrumentalist"
        autowire="byName">
            <property name="song" value="Jingle Bells" />
    </bean>
    
    <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-2.5.xsd"
    	default-autowire="byName">
     

 设置bean的自动装配策略:

  • primary="false":不会优先进行匹配。默认为true
  • autowire-candidate="false":不会进行匹配

 2.Wiring with annotations

打开Spring的注解装配机制:

  • <context:annotation-config />

 

spring支持的自动装配注解:

  • @Autowired:配合 @Qualifier 使用,更健康
  • @Inject:from JSR-330
  • @Resource: from JSR-250

Autowired注解:

  • 不需要设置setXXX方法了;默认类型为byType
  • 既可以设置在字段上,私有字段也可以;也可以设置在方法上:此时还是一般设置在setXXX方法上。
  • 配置策略:@Autowired(required=false) 可以不匹配成功
  •  @Qualifier :其实就是将Autowired变成byName的方式来使用;可以用于类的限定或者配合Autowired来使用:
    @Qualifier("stringed")
    public class Guitar implements Instrument {
    ...
    }
  • @Autowired
    @Qualifier("guitar")
    private Instrument instrument;
     

Qualifier的高级使用情况:使用@Qualifier自定义自己的限制注解:

@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface StringedInstrument 
{

}

则在代码中可以使用@StringedInstrument来进一步缩小范围
@StringedInstrument
public class Guitar implements Instrument {
...
}

@Autowired
@StringedInstrument
private Instrument instrument;

 3.Automatically discovering beans

使用自动发现机制,更加能减少XML的配置:

<context:component-scan>:The <context:component-scan> element does everything that <context:annotation-config> does, plus it configures Spring to automatically discover beans and declare them for you:

  • @Component
  • @Controller
  • @Repository
  • @Service

过滤component-scan:

<context:include-filter>:

 <context:exclude-filter>:

 

 

猜你喜欢

转载自cxmqq333.iteye.com/blog/1871738