Spring - @Autowired与@Resource

1、@Autowiredjava

spring2.5引入@Autowired 注解。用于对类的成员变量,方法及构造函数进行注入。取代了get、set方法: spring

// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);

// use configured instance
List<String> userList = service.getUsernameList();

注解形式函数

@Autowired             默认byType形式
@Autowired @Qualifier("beanId")  使用byName形式
@Autowired( required=false)     使用byType形式,注入值不存在,能够为nullui

2、@Resourcethis

JSR-250 注解prototype

注解形式code

@Resource             默认byName形式
@Resource(name="loginService")   使用byName形式
@Resource(type="")         使用byType形式xml

注意:
@Resource 默认byName 注入。name能够是字段名。当找不到匹配的bean才按类型装配。对象

3、细节问题资源

@Autowired ( autowire属性 )

byType       发现多个bean或没有,抛异常
byName      指定名称,没有,抛异常
Contructor     没有,抛异常
autodetect     决定默认状况下,用byType仍是Contructor

@Resource

@Autowired 相似,不过@Resource 默认按照名称式匹配,匹配不成功能够按照类型匹配,固然若是指定了name,则只按名称进行匹配。

@Service
使用组件扫描时,默认将使用此注解的类的第一字母小写做为bean的id生成bean。能够使用@Service("myName"),指定要生成的bean的id。

@Scope
在配置bean时,能够对其做用域进行限制。 默认为singleton,单一实例。也能够设置做用域为 prototype,任意数量的对象实例。

<!-- A bean definition with singleton scope -->
<bean id="..." class="..." scope="singleton">
    <!-- collaborators and configuration for this bean go here -->
</bean>

除了,在配置文件中进行配置。还能够使用注解:

@Service("userXxx")@Scope("prototype")

public class UserServiceImpl implements UserXxx {

……

}

在添加注解的相应的类中,若是想初始化或销毁某个方法,咱们能够直接在方法上添加注解,以下:

@PostConstruct

public void addItem() {

System.out.println("初始化方法");

}

``` @PreDestroy

public void testItem() {

System.out.println("释放资源");

} ```

原文

相关文章
相关标签/搜索