想学一学Spring mvc 。现在先找找框架试试水。
@Autowired注入属性(可以加在:属性,方法,构造方法上,如果不确定他将插入spring context中 则有可选属性( @Autowired(required = false)))
Spring 容器中配置了两个类型为 Office
类型的 Bean,当对 Boss 的 office
成员变量进行自动注入时,Spring 容器将无法确定到底要用哪一个 Bean,因此异常发生了。
Spring 允许我们通过 @Qualifier
注释指定注入 Bean 的名称,这样歧义就消除了,可以通过下面的方法解决异常:
@Autowired public void setOffice(@Qualifier("office")Office office) { this.office = office; }也是属性,方法,构造方法,
@Resource
@Resource
的作用相当于 @Autowired
,只不过 @Autowired
按 byType 自动注入,面 @Resource
默认按 byName 自动注入罢了。@Resource
有两个属性是比较重要的,分别是 name 和 type,Spring 将 @Resource
注释的 name 属性解析为 Bean 的名字,而 type 属性则解析为 Bean 的类型。所以如果使用 name 属性,则使用 byName 的自动注入策略,而使用 type 属性时则使用 byType 自动注入策略。如果既不指定 name 也不指定 type 属性,这时将通过反射机制使用 byName 自动注入策略。
@PostConstruct 和 @PreDestroy
初始化,和销毁方法(析构函数)
package com.baobaotao; import javax.annotation.Resource; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; public class Boss { @Resource private Car car; @Resource(name = "office") private Office office; @PostConstruct public void postConstruct1(){ System.out.println("postConstruct1"); } @PreDestroy public void preDestroy1(){ System.out.println("preDestroy1"); } … }只需要在方法前标注
@PostConstruct
或
@PreDestroy
,这些方法就会在 Bean 初始化后或销毁之前被 Spring 容器执行了。
@Component
package com.baobaotao; import org.springframework.stereotype.Component; @Component public class Car { … }替代xml bean
xml配置检测目录
<context:component-scan base-package="com.baobaotao"/>
扫描方式
表 1. 扫描过滤方式
过滤器类型 | 说明 |
---|---|
注释 | 假如 com.baobaotao.SomeAnnotation 是一个注释类,我们可以将使用该注释的类过滤出来。 |
类名指定 | 通过全限定类名进行过滤,如您可以指定将 com.baobaotao.Boss 纳入扫描,而将 com.baobaotao.Car 排除在外。 |
正则表达式 | 通过正则表达式定义过滤的类,如下所示:com\.baobaotao\.Default.* |
AspectJ 表达式 | 通过 AspectJ 表达式定义过滤的类,如下所示:com. baobaotao..*Service+ |
下面是一个简单的例子:
<context:component-scan base-package="com.baobaotao"> <context:include-filter type="regex" expression="com\.baobaotao\.service\..*"/> <context:exclude-filter type="aspectj" expression="com.baobaotao.util..*"/> </context:component-scan>@Scope 指定 Bean 的作用范围
package com.baobaotao; import org.springframework.context.annotation.Scope; … @Scope("prototype") @Component("boss") public class Boss { … }