1、启动注解:
在Spring配置文件中添加:
1)、文件头添加:
xsi:schemaLocation="
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-.5.xsd
2)、添加启动自动注解的配置:
<!-- 配置注解处理器,开启注解 -->
<context:annotation-config/>
3)、添加自动注解的扫描路径:
<!-- 配置bean扫描器 ,自动扫描处理 [需要实现注入的包]-->
<context:component-scan base-package="com.youProjectPackage.*" />
配置过程完成。
接下来是关于在bean、dao、service、controller[action]中的注解操作解释:
对于引入变量:[以user表为例,这理由userName、userNum变量]
userDao中要引入userName:
在spring配置文件中添加:
<bean id="user" class="com.kaide.workflow.user.bean.User"></bean>
userDao中:
@Autowired
private User user;
user变量就可以使用啦!
如果是在spring中没有配置userBean则会抛出:BeanCreationException 异常。
这时候若是要忽略这一异常则:@Autowired(required=false)[不提倡!]
@Autowired
@Qualifier("user")//指定注入变量名称
private User user;
@Qualifier 只能和 @Autowired 结合使用,是对 @Autowired 有益的补充。一般来讲,@Qualifier 对方法签名中入参进行注释会降低代码的可读性,而对成员变量注释则相对好一些。
@Resource 的作用相当于 @Autowired,只不过 @Autowired 按 byType 自动注入,面 @Resource 默认按 byName 自动注入罢了。@Resource 有两个属性是比较重要的,分别是 name 和 type,Spring 将 @Resource 注释的 name 属性解析为 Bean 的名字,而 type 属性则解析为 Bean 的类型。所以如果使用 name 属性,则使用 byName 的自动注入策略,而使用 type 属性时则使用 byType 自动注入策略。如果既不指定 name 也不指定 type 属性,这时将通过反射机制使用 byName 自动注入策略。
// 自动注入类型为 User 的 Bean
@Resource
private User user;
// 自动注入 bean 名称为 user的 Bean
@Resource(name = "user")
private Office user;
使用@Autwired并且每次注入的都是新的实例
被注入的类:
@Scope("prototype")
@Repository
public class User {
注入到的类中的声明方式:
@Autowired
private User user;