首 页 行业热点 新车 试驾评测 养车用车 车型库

@autowired注解 怎么生效

发布网友

我来回答

1个回答

热心网友

使用Spring时,通过Spring注入的Bean一般都被定义成private,并且要有getter和setter方法,显得比较繁琐,增加了代码量,而且有时会搞忘造成错误。

可以使用@Autowired注解来减少代码量。首先,在applicationContext中加入:

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
Spring使用这个BeanPostProcessor解析@Autowired注解。

然后,在变量上添加@Autowired注解,并去掉相应的getter和setter方法:

复制代码
package com.school.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.school..ClasDAO;
import com.school.entity.Clas;

public class ClasServiceImpl implements ClasService{

@Autowired
private ClasDAO clasDAO;

  ...

}
复制代码
并且在applicationContext中将相应的<property></property>标签去掉:

<bean id="clasService" class="com.school.service.ClasServiceImpl">
</bean>
Spring启动时,AutowiredAnnotationBeanPostProcessor会扫描所有的Bean,当发现其中有@Autowired注解时,就会找相应类型的Bean,并且实现注入。

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com