内容简介:其中base-package为需要扫描的包(含子包)。@Configuration把一个类作为一个IoC容器,它的某个方法头上如果注册了@Bean,就会作为这个Spring容器中的Bean。@Scope注解 作用域
其中base-package为需要扫描的包(含子包)。
<context:component-scan base-package="cn.test"/>
@Configuration把一个类作为一个IoC容器,它的某个方法头上如果注册了@Bean,就会作为这个Spring容器中的Bean。
@Scope注解 作用域
@Lazy(true) 表示延迟初始化
@Service用于标注业务层组件、
@Controller用于标注控制层组件(如struts中的action)
@Repository用于标注数据访问组件,即DAO组件。
@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
@Scope用于指定scope作用域的(用在类上)
—————jsr250—-
@PostConstruct用于指定初始化方法(用在方法上)
@PreDestory用于指定销毁方法(用在方法上)
@Resource 默认按名称装配,当找不到与名称匹配的bean才会按类型装配。
———-
@DependsOn:定义Bean初始化及销毁时的顺序
@Primary:自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常
@Autowired 默认按类型装配,如果我们想使用按名称装配,可以结合@Qualifier注解一起使用。如下:@Autowired @Qualifier(“personDaoBean”) 存在多个实例配合使用
@PostConstruct 初始化注解
@PreDestroy 摧毁注解 默认 单例 启动就加载??
@Async异步方法调用,需要添加以下代码:
<bean id=
"taskExecutor"
class
=
"org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"
>
<property name=
"corePoolSize"
value=
"10"
/>
<property name=
"maxPoolSize"
value=
"300"
/>
</bean>
<task:annotation-driven/>
为了让@Async注解能够生效,还需要在Spring Boot的主程序中配置@EnableAsync
在Spring中,基于@Async标注的方法,称之为异步方法;
这些方法将在执行的时候,将会在独立的线程中被执行,
调用者无需等待它的完成,
即可继续其他的操作。
@Async所修饰的函数不要定义为static类型,这样异步调用不会生效
@ComponentScan(basePackages = "com.xzc.") @EnableAutoConfiguration @SpringBootApplication @PropertySource({"classpath:application.properties", "classpath:xzc.properties"}) @ImportResource("classpath:ws-client.xml") @EnableRedisHttpSession @EnableAspectJAutoProxy @EnableCaching @EnableAsync @Configuration
@EnableScheduling 启动定时任务
@Entity注释指名这是一个实体Bean
@SuppressWarnings注解?
1、 @PathVariable
当使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId}, 这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上
- @Controller
- @RequestMapping( “/owners/{ownerId}”)
- public class RelativePathUriTemplateController {
- @RequestMapping( “/pets/{petId}”)
- public void findPet( @PathVariable String ownerId, @PathVariable String petId, Model model) {
- // implementation omitted
- }
上面代码把URI template 中变量 ownerId的值和petId的值,绑定到方法的参数上。
若方法参数名称和需要绑定的uri template中变量名称不一致,需要在@PathVariable(“name”)指定uri template中的名称。
Spring 4.2新特性-使用@Order调整配置类加载顺序
—————————————————-
lombok 简化 java 代码注解 理解
lombok 注解:
lombok 提供的注解不多,可以参考官方视频的讲解和官方文档。
Lombok 注解在线帮助文档:http://projectlombok.org/features/index.
下面介绍几个我常用的 lombok 注解:
@Data :注解在类上;提供类所有属性的 getting 和 setting 方法,此外还提供了equals、canEqual、hashCode、toString 方法
@Setter:注解在属性上;为属性提供 setting 方法
@Getter:注解在属性上;为属性提供 getting 方法
@Log4j :注解在类上;为类提供一个 属性名为log 的 log4j 日志对象
@NoArgsConstructor:注解在类上;为类提供一个无参的构造方法
@AllArgsConstructor:注解在类上;为类提供一个全参的构造方法
==================================
Spring 注解详细分析解释有实例
概述
注释配置相对于 XML 配置具有很多的优势:
- 它可以充分利用 Java 的反射机制获取类结构信息,这些信息可以有效减少配置的工作。如使用 JPA 注释配置 ORM 映射时,我们就不需要指定 PO 的属性名、类型等信息,如果关系表字段和 PO 属性名、类型都一致,您甚至无需编写任务属性映射信息——因为这些信息都可以通过 Java 反射机制获取。
- 注释和 Java 代码位于一个文件中,而 XML 配置采用独立的配置文件,大多数配置信息在程序开发完成后都不会调整,如果配置信息和 Java 代码放在一起,有助于增强程序的内聚性。而采用独立的 XML 配置文件,程序员在编写一个功能时,往往需要在程序文件和配置文件中不停切换,这种思维上的不连贯会降低开发效率。
因此在很多情况下,注释配置比 XML 配置更受欢迎,注释配置有进一步流行的趋势。Spring 2.5 的一大增强就是引入了很多注释类,现在您已经可以使用注释配置完成大部分 XML 配置的功能。在这篇文章里,我们将向您讲述使用注释进行 Bean 定义和依赖注入的内容。
原来我们是怎么做的
在使用注释配置之前,先来回顾一下传统上是如何配置 Bean 并完成 Bean 之间依赖关系的建立。下面是 3 个类,它们分别是 Office、Car 和 Boss,这 3 个类需要在 Spring 容器中配置为 Bean:
Office 仅有一个属性:
清单 1. Office.java
package com.baobaotao; public class Office { private String officeNo =”001”; //省略 get/setter @Override public String toString() { return "officeNo:" + officeNo; } }
Car 拥有两个属性:
清单 2. Car.java
package com.baobaotao; public class Car { private String brand; private double price; // 省略 get/setter @Override public String toString() { return "brand:" + brand + "," + "price:" + price; } }
Boss 拥有 Office 和 Car 类型的两个属性:
清单 3. Boss.java
package com.baobaotao; public class Boss { private Car car; private Office office; // 省略 get/setter @Override public String toString() { return "car:" + car + "\n" + "office:" + office; } }
我们在 Spring 容器中将 Office 和 Car 声明为 Bean,并注入到 Boss Bean 中:下面是使用传统 XML 完成这个工作的配置文件 beans.xml:
清单 4. beans.xml 将以上三个类配置成 Bean
<?xml version="1.0" encoding="UTF-8" ?> <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"> <bean id="boss" class="com.baobaotao.Boss"> <property name="car" ref="car"/> <property name="office" ref="office" /> </bean> <bean id="office" class="com.baobaotao.Office"> <property name="officeNo" value="002"/> </bean> <bean id="car" class="com.baobaotao.Car" scope="singleton"> <property name="brand" value=" 红旗 CA72"/> <property name="price" value="2000"/> </bean> </beans>
当我们运行以下代码时,控制台将正确打出 boss 的信息:
清单 5. 测试类:AnnoIoCTest.java
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class AnnoIoCTest { public static void main(String[] args) { String[] locations = {"beans.xml"}; ApplicationContext ctx = new ClassPathXmlApplicationContext(locations); Boss boss = (Boss) ctx.getBean("boss"); System.out.println(boss); } }
这说明 Spring 容器已经正确完成了 Bean 创建和装配的工作。
使用 @Autowired 注释
Spring 2.5 引入了 @Autowired
注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。来看一下使用 @Autowired
进行成员变量自动注入的代码:
清单 6. 使用 @Autowired 注释的 Boss.java
package com.baobaotao; import org.springframework.beans.factory.annotation.Autowired; public class Boss { @Autowired private Car car; @Autowired private Office office; … }
Spring 通过一个 BeanPostProcessor
对 @Autowired
进行解析,所以要让 @Autowired
起作用必须事先在 Spring 容器中声明 AutowiredAnnotationBeanPostProcessor
Bean。
清单 7. 让 @Autowired 注释工作起来
<?xml version="1.0" encoding="UTF-8" ?> <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"> <!-- 该 BeanPostProcessor 将自动起作用,对标注 @Autowired 的 Bean 进行自动注入 --> <bean class="org.springframework.beans.factory.annotation. AutowiredAnnotationBeanPostProcessor"/> <!-- 移除 boss Bean 的属性注入配置的信息 --> <bean id="boss" class="com.baobaotao.Boss"/> <bean id="office" class="com.baobaotao.Office"> <property name="officeNo" value="001"/> </bean> <bean id="car" class="com.baobaotao.Car" scope="singleton"> <property name="brand" value=" 红旗 CA72"/> <property name="price" value="2000"/> </bean> </beans>
这样,当 Spring 容器启动时, AutowiredAnnotationBeanPostProcessor
将扫描 Spring 容器中所有 Bean,当发现 Bean 中拥有 @Autowired
注释时就找到和其匹配(默认按类型匹配)的 Bean,并注入到对应的地方中去。
按照上面的配置,Spring 将直接采用 Java 反射机制对 Boss 中的 car
和 office
这两个私有成员变量进行自动注入。所以对成员变量使用 @Autowired
后,您大可将它们的 setter 方法( setCar()
和 setOffice()
)从 Boss 中删除。
当然,您也可以通过 @Autowired
对方法或构造函数进行标注,来看下面的代码:
清单 8. 将 @Autowired 注释标注在 Setter 方法上
package com.baobaotao; public class Boss { private Car car; private Office office; @Autowired public void setCar(Car car) { this.car = car; } @Autowired public void setOffice(Office office) { this.office = office; } … }
这时, @Autowired
将查找被标注的方法的入参类型的 Bean,并调用方法自动注入这些 Bean。而下面的使用方法则对构造函数进行标注:
清单 9. 将 @Autowired 注释标注在构造函数上
package com.baobaotao; public class Boss { private Car car; private Office office; @Autowired public Boss(Car car ,Office office){ this.car = car; this.office = office ; } … }
由于 Boss()
构造函数有两个入参,分别是 car
和 office
, @Autowired
将分别寻找和它们类型匹配的 Bean,将它们作为 Boss(Car car ,Office office)
的入参来创建 Boss
Bean。
当候选 Bean 数目不为 1 时的应对方法
在默认情况下使用 @Autowired
注释进行自动注入时,Spring 容器中匹配的候选 Bean 数目必须有且仅有一个。当找不到一个匹配的 Bean 时,Spring 容器将抛出 BeanCreationException
异常,并指出必须至少拥有一个匹配的 Bean。我们可以来做一个实验:
清单 10. 候选 Bean 数目为 0 时
<?xml version="1.0" encoding="UTF-8" ?> <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 "> <bean class="org.springframework.beans.factory.annotation. AutowiredAnnotationBeanPostProcessor"/> <bean id="boss" class="com.baobaotao.Boss"/> <!-- 将 office Bean 注释掉 --> <!-- <bean id="office" class="com.baobaotao.Office"> <property name="officeNo" value="001"/> </bean>--> <bean id="car" class="com.baobaotao.Car" scope="singleton"> <property name="brand" value=" 红旗 CA72"/> <property name="price" value="2000"/> </bean> </beans>
由于 office
Bean 被注释掉了,所以 Spring 容器中将没有类型为 Office
的 Bean 了,而 Boss 的 office
属性标注了 @Autowired
,当启动 Spring 容器时,异常就产生了。
当不能确定 Spring 容器中一定拥有某个类的 Bean 时,可以在需要自动注入该类 Bean 的地方可以使用 @Autowired(required = false)
,这等于告诉 Spring:在找不到匹配 Bean 时也不报错。来看一下具体的例子:
清单 11. 使用 @Autowired(required = false)
package com.baobaotao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Required; public class Boss { private Car car; private Office office; @Autowired public void setCar(Car car) { this.car = car; } @Autowired(required = false) public void setOffice(Office office) { this.office = office; } … }
当然,一般情况下,使用 @Autowired
的地方都是需要注入 Bean 的,使用了自动注入而又允许不注入的情况一般仅会在开发期或测试期碰到(如为了快速启动 Spring 容器,仅引入一些模块的 Spring 配置文件),所以 @Autowired(required = false)
会很少用到。
和找不到一个类型匹配 Bean 相反的一个错误是:如果 Spring 容器中拥有多个候选 Bean,Spring 容器在启动时也会抛出 BeanCreationException
异常。来看下面的例子:
清单 12. 在 beans.xml 中配置两个 Office 类型的 Bean
… <bean id="office" class="com.baobaotao.Office"> <property name="officeNo" value="001"/> </bean> <bean id="office2" class="com.baobaotao.Office"> <property name="officeNo" value="001"/> </bean> …
我们在 Spring 容器中配置了两个类型为 Office
类型的 Bean,当对 Boss 的 office
成员变量进行自动注入时,Spring 容器将无法确定到底要用哪一个 Bean,因此异常发生了。
Spring 允许我们通过 @Qualifier
注释指定注入 Bean 的名称,这样歧义就消除了,可以通过下面的方法解决异常:
清单 13. 使用 @Qualifier 注释指定注入 Bean 的名称
@Autowired public void setOffice(@Qualifier("office")Office office) { this.office = office; }
@Qualifier("office")
中的 office
是 Bean 的名称,所以 @Autowired
和 @Qualifier
结合使用时,自动注入的策略就从 byType 转变成 byName 了。
@Autowired
可以对成员变量、方法以及构造函数进行注释,而 @Qualifier
的标注对象是成员变量、方法入参、构造函数入参。正是由于注释对象的不同,所以 Spring 不将 @Autowired
和 @Qualifier
统一成一个注释类。下面是对成员变量和构造函数入参进行注释的代码:
对成员变量进行注释:
清单 14. 对成员变量使用 @Qualifier 注释
public class Boss { @Autowired private Car car; @Autowired @Qualifier("office") private Office office; … }
对构造函数入参进行注释:
清单 15. 对构造函数变量使用 @Qualifier 注释
public class Boss { private Car car; private Office office; @Autowired public Boss(Car car , @Qualifier("office")Office office){ this.car = car; this.office = office ; } }
@Qualifier
只能和 @Autowired
结合使用,是对 @Autowired
有益的补充。一般来讲, @Qualifier
对方法签名中入参进行注释会降低代码的可读性,而对成员变量注释则相对好一些。
使用 JSR-250 的注释
Spring 不但支持自己定义的 @Autowired
的注释,还支持几个由 JSR-250 规范定义的注释,它们分别是 @Resource
、 @PostConstruct
以及 @PreDestroy
。
@Resource
@Resource
的作用相当于 @Autowired
,只不过 @Autowired
按 byType 自动注入,面 @Resource
默认按 byName 自动注入罢了。 @Resource
有两个属性是比较重要的,分别是 name 和 type,Spring 将 @Resource
注释的 name 属性解析为 Bean 的名字,而 type 属性则解析为 Bean 的类型。所以如果使用 name 属性,则使用 byName 的自动注入策略,而使用 type 属性时则使用 byType 自动注入策略。如果既不指定 name 也不指定 type 属性,这时将通过反射机制使用 byName 自动注入策略。
Resource 注释类位于 Spring 发布包的 lib/j2ee/common-annotations.jar 类包中,因此在使用之前必须将其加入到项目的类库中。来看一个使用 @Resource
的例子:
清单 16. 使用 @Resource 注释的 Boss.java
package com.baobaotao; import javax.annotation.Resource; public class Boss { // 自动注入类型为 Car 的 Bean @Resource private Car car; // 自动注入 bean 名称为 office 的 Bean @Resource(name = "office") private Office office; }
一般情况下,我们无需使用类似于 @Resource(type=Car.class)
的注释方式,因为 Bean 的类型信息可以通过 Java 反射从代码中获取。
要让 JSR-250 的注释生效,除了在 Bean 类中标注这些注释外,还需要在 Spring 容器中注册一个负责处理这些注释的 BeanPostProcessor
:
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
CommonAnnotationBeanPostProcessor
实现了 BeanPostProcessor
接口,它负责扫描使用了 JSR-250 注释的 Bean,并对它们进行相应的操作。
@PostConstruct 和 @PreDestroy
Spring 容器中的 Bean 是有生命周期的,Spring 允许在 Bean 在初始化完成后以及 Bean 销毁前执行特定的操作,您既可以通过实现 InitializingBean/DisposableBean 接口来定制初始化之后 / 销毁之前的操作方法,也可以通过 <bean> 元素的 init-method/destroy-method 属性指定初始化之后 / 销毁之前调用的操作方法。关于 Spring 的生命周期,笔者在《精通 Spring 2.x—企业应用开发精解》第 3 章进行了详细的描述,有兴趣的读者可以查阅。
JSR-250 为初始化之后/销毁之前方法的指定定义了两个注释类,分别是 @PostConstruct 和 @PreDestroy,这两个注释只能应用于方法上。标注了 @PostConstruct 注释的方法将在类实例化后调用,而标注了 @PreDestroy 的方法将在类销毁之前调用。
清单 17. 使用 @PostConstruct 和 @PreDestroy 注释的 Boss.java
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 容器执行了。
我们知道,不管是通过实现 InitializingBean
/ DisposableBean
接口,还是通过 <bean> 元素的 init-method/destroy-method
属性进行配置,都只能为 Bean 指定一个初始化 / 销毁的方法。但是使用 @PostConstruct
和 @PreDestroy
注释却可以指定多个初始化 / 销毁方法,那些被标注 @PostConstruct
或 @PreDestroy
注释的方法都会在初始化 / 销毁时被执行。
通过以下的测试代码,您将可以看到 Bean 的初始化 / 销毁方法是如何被执行的:
清单 18. 测试类代码
package com.baobaotao; import org.springframework.context.support.ClassPathXmlApplicationContext; public class AnnoIoCTest { public static void main(String[] args) { String[] locations = {"beans.xml"}; ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(locations); Boss boss = (Boss) ctx.getBean("boss"); System.out.println(boss); ctx.destroy();// 关闭 Spring 容器,以触发 Bean 销毁方法的执行 } }
这时,您将看到标注了 @PostConstruct
的 postConstruct1()
方法将在 Spring 容器启动时,创建 Boss
Bean 的时候被触发执行,而标注了 @PreDestroy
注释的 preDestroy1()
方法将在 Spring 容器关闭前销毁 Boss
Bean 的时候被触发执行。
使用 <context:annotation-config/> 简化配置
Spring 2.1 添加了一个新的 context 的 Schema 命名空间,该命名空间对注释驱动、属性文件引入、加载期织入等功能提供了便捷的配置。我们知道注释本身是不会做任何事情的,它仅提供元数据信息。要使元数据信息真正起作用,必须让负责处理这些元数据的处理器工作起来。
而我们前面所介绍的 AutowiredAnnotationBeanPostProcessor
和 CommonAnnotationBeanPostProcessor
就是处理这些注释元数据的处理器。但是直接在 Spring 配置文件中定义这些 Bean 显得比较笨拙。Spring 为我们提供了一种方便的注册这些 BeanPostProcessor
的方式,这就是 <context:annotation-config/>。请看下面的配置:
清单 19. 调整 beans.xml 配置文件
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:annotation-config/> <bean id="boss" class="com.baobaotao.Boss"/> <bean id="office" class="com.baobaotao.Office"> <property name="officeNo" value="001"/> </bean> <bean id="car" class="com.baobaotao.Car" scope="singleton"> <property name="brand" value=" 红旗 CA72"/> <property name="price" value="2000"/> </bean> </beans>
<context:annotationconfig/> 将隐式地向 Spring 容器注册 AutowiredAnnotationBeanPostProcessor
、 CommonAnnotationBeanPostProcessor
、 PersistenceAnnotationBeanPostProcessor
以及 equiredAnnotationBeanPostProcessor
这 4 个 BeanPostProcessor。
在配置文件中使用 context 命名空间之前,必须在 <beans> 元素中声明 context 命名空间。
使用 @Component
虽然我们可以通过 @Autowired
或 @Resource
在 Bean 类中使用自动注入功能,但是 Bean 还是在 XML 文件中通过 <bean> 进行定义 —— 也就是说,在 XML 配置文件中定义 Bean,通过 @Autowired
或 @Resource
为 Bean 的成员变量、方法入参或构造函数入参提供自动注入的功能。能否也通过注释定义 Bean,从 XML 配置文件中完全移除 Bean 定义的配置呢?答案是肯定的,我们通过 Spring 2.5 提供的 @Component
注释就可以达到这个目标了。
为什么 @Repository 只能标注在 DAO 类上呢?这是因为该注解的作用不只是将类识别为 Bean,同时它还能将所标注的类中抛出的数据访问异常封装为 Spring 的数据访问异常类型。 Spring 本身提供了一个丰富的并且是与具体的数据访问技术无关的数据访问异常结构,用于封装不同的持久层框架抛出的异常,使得异常独立于底层的框架。
Spring 2.5 在 @Repository 的基础上增加了功能类似的额外三个注解:@Component、@Service、@Constroller,它们分别用于软件系统的不同层次:
- @Component 是一个泛化的概念,仅仅表示一个组件 (Bean) ,可以作用在任何层次。
- @Service 通常作用在业务层,但是目前该功能与 @Component 相同。
- @Constroller 通常作用在控制层,但是目前该功能与 @Component 相同。
通过在类上使用 @Repository、@Component、@Service 和 @Constroller 注解,Spring 会自动创建相应的 BeanDefinition 对象,并注册到 ApplicationContext 中。这些类就成了 Spring 受管组件。这三个注解除了作用于不同软件层次的类,其使用方式与 @Repository 是完全相同的。
下面,我们完全使用注释定义 Bean 并完成 Bean 之间装配:
清单 20. 使用 @Component 注释的 Car.java
package com.baobaotao; import org.springframework.stereotype.Component; @Component public class Car { … }
仅需要在类定义处,使用 @Component
注释就可以将一个类定义了 Spring 容器中的 Bean。下面的代码将 Office
定义为一个 Bean:
清单 21. 使用 @Component 注释的 Office.java
package com.baobaotao; import org.springframework.stereotype.Component; @Component public class Office { private String officeNo = "001"; … }
这样,我们就可以在 Boss 类中通过 @Autowired
注入前面定义的 Car
和 Office Bean
了。
清单 22. 使用 @Component 注释的 Boss.java
package com.baobaotao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Required; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; @Component("boss") public class Boss { @Autowired private Car car; @Autowired private Office office; … }
@Component
有一个可选的入参,用于指定 Bean 的名称,在 Boss 中,我们就将 Bean 名称定义为“ boss
”。一般情况下,Bean 都是 singleton 的,需要注入 Bean 的地方仅需要通过 byType 策略就可以自动注入了,所以大可不必指定 Bean 的名称。
在使用 @Component
注释后,Spring 容器必须启用类扫描机制以启用注释驱动 Bean 定义和注释驱动 Bean 自动注入的策略。Spring 2.5 对 context 命名空间进行了扩展,提供了这一功能,请看下面的配置:
清单 23. 简化版的 beans.xml
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:component-scan base-package="com.baobaotao"/> </beans>
这里,所有通过 <bean> 元素定义 Bean 的配置内容已经被移除,仅需要添加一行 <context:component-scan/> 配置就解决所有问题了——Spring XML 配置文件得到了极致的简化(当然配置元数据还是需要的,只不过以注释形式存在罢了)。<context:component-scan/> 的 base-package 属性指定了需要扫描的类包,类包及其递归子包中所有的类都会被处理。
<context:component-scan/> 还允许定义过滤器将基包下的某些类纳入或排除。Spring 支持以下 4 种类型的过滤方式,通过下表说明:
表 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>
值得注意的是 <context:component-scan/> 配置项不但启用了对类包进行扫描以实施注释驱动 Bean 定义的功能,同时还启用了注释驱动自动注入的功能(即还隐式地在内部注册了 AutowiredAnnotationBeanPostProcessor
和 CommonAnnotationBeanPostProcessor
),因此当使用 <context:component-scan/> 后,就可以将 <context:annotation-config/> 移除了。
默认情况下通过 @Component
定义的 Bean 都是 singleton 的,如果需要使用其它作用范围的 Bean,可以通过 @Scope
注释来达到目标,如以下代码所示:
@scopee
清单 24. 通过 @Scope 指定 Bean 的作用范围
package com.baobaotao; import org.springframework.context.annotation.Scope; … @Scope("prototype") @Component("boss") public class Boss { … }
这样,当从 Spring 容器中获取 boss
Bean 时,每次返回的都是新的实例了。
采用具有特殊语义的注释
Spring 2.5 中除了提供 @Component
注释外,还定义了几个拥有特殊语义的注释,它们分别是: @Repository
、 @Service
和 @Controller
。在目前的 Spring 版本中,这 3 个注释和 @Component
是等效的,但是从注释类的命名上,很容易看出这 3 个注释分别和持久层、业务层和控制层(Web 层)相对应。虽然目前这 3 个注释和 @Component
相比没有什么新意,但 Spring 将在以后的版本中为它们添加特殊的功能。所以,如果 Web 应用程序采用了经典的三层分层结构的话,最好在持久层、业务层和控制层分别采用 @Repository
、 @Service
和 @Controller
对分层中的类进行注释,而用 @Component
对那些比较中立的类进行注释。
注释配置和 XML 配置的适用场合
是否有了这些 IOC 注释,我们就可以完全摒除原来 XML 配置的方式呢?答案是否定的。有以下几点原因:
- 注释配置不一定在先天上优于 XML 配置。如果 Bean 的依赖关系是固定的,(如 Service 使用了哪几个 DAO 类),这种配置信息不会在部署时发生调整,那么注释配置优于 XML 配置;反之如果这种依赖关系会在部署时发生调整,XML 配置显然又优于注释配置,因为注释是对 Java 源代码的调整,您需要重新改写源代码并重新编译才可以实施调整。
-
如果 Bean 不是自己编写的类(如
JdbcTemplate
、SessionFactoryBean
等),注释配置将无法实施,此时 XML 配置是唯一可用的方式。 -
注释配置往往是类级别的,而 XML 配置则可以表现得更加灵活。比如相比于
@Transaction
事务注释,使用 aop/tx 命名空间的事务配置更加灵活和简单。
所以在实现应用中,我们往往需要同时使用注释配置和 XML 配置,对于类级别且不会发生变动的配置可以优先考虑注释配置;而对于那些第三方类以及容易发生调整的配置则应优先考虑使用 XML 配置。Spring 会在具体实施 Bean 创建和 Bean 注入之前将这两种配置方式的元信息融合在一起。
来源: https://www.cnblogs.com/xingzc/p/5777814.html
———————–
Spring常用注解汇总
@Controller:注册一个bean到spring(一般用于Controller层)
@Service:注册一个bean到spring(一般用于service层)
@Repository:注册一个bean到spring(一般用于dao层)
@Component (不推荐使用):注册一个bean到spring,一般使用前三个来指示不同层的bean
@Autowired
@Resource
@RequestMapping
@RequestParam
@Scope
@PathVariable:用于对应restful风格url中的参数
@ModelAttribute
@Cacheable: @Cacheable注解在spring3中的使用-实现缓存
@CacheFlush:清空缓存
@PostConstruct:
@PreDestroy
@SessionAttributes
@InitBinder
@Required
@Qualifier
• 例如
@Controller
public class SoftCreateController extends SimpleBaseController {}
• 或者
@Controller(“userController”)
• 说明
@Controller 负责注册一个bean 到spring 上下文中,bean 的ID 默认为类名称开头字母小写
@Service
• 例如
@Service
public class SoftCreateServiceImpl implements ISoftCreateService {}
• 或者
@Service(“softCreateServiceImpl”)
• 说明
@Service 负责注册一个bean 到spring 上下文中,bean 的ID 默认为类名称开头字母小写
@Autowired
• 例如
@Autowired
private ISoftPMService softPMService;
• 或者
@Autowired(required=false)
private ISoftPMService softPMService = new SoftPMServiceImpl();
• 说明
@Autowired 根据bean 类型从spring 上线文中进行查找,注册类型必须唯一,否则报异常。
与@Resource 的区别在于,@Resource 允许通过bean 名称或bean 类型两种方式进行查找@Autowired(required=false) 表示,如果spring 上下文中没有找到该类型的bean 时, 才会使用new SoftPMServiceImpl();
@Autowired 标注作用于 Map 类型时,如果 Map 的 key 为 String 类型,则 Spring 会将容器中所有类型符合 Map 的 value 对应的类型的 Bean 增加进来,用 Bean 的 id 或 name 作为 Map 的 key。
@Autowired 还有一个作用就是,如果将其标注在 BeanFactory 类型、ApplicationContext 类型、ResourceLoader 类型、ApplicationEventPublisher 类型、MessageSource 类型上,那么 Spring 会自动注入这些实现类的实例,不需要额外的操作。
@RequestMapping
• 类
@Controller
@RequestMapping(“/bbtForum.do”) 本文来自www.itxxz.com
public class BbtForumController {
@RequestMapping(params = “method=listBoardTopic”)
public String listBoardTopic(int topicId,User user) {}
}
• 方法
@RequestMapping(“/softpg/downSoftPg.do”)
@RequestMapping(value=”/softpg/ajaxLoadSoftId.do”,method = POST)
@RequestMapping(value = “/osu/product/detail.do”, params = { “modify=false” }, method =POST)
• 说明
@RequestMapping 可以声明到类或方法上
• 参数绑定说明
如果我们使用以下的 URL 请求:
http://localhost/ itxxzSpring4 ?method=listBoardTopic&topicId=1&userId=10&userName=tom copyright www.itxxz.com
topicId URL 参数将绑定到 topicId 入参上,而 userId 和 userName URL 参数将绑定到 user 对象的 userId 和 userName 属性中。和 URL 请求中不允许没有 topicId 参数不同,虽然 User 的 userId 属性的类型是基本数据类型,但如果 URL 中不存在 userId 参数,Spring 也不会报错,此时 user.userId 值为 0 。如果 User 对象拥有一个 dept.deptId 的级联属性,那么它将和 dept.deptId URL 参数绑定。
@RequestParam
• 参数绑定说明
@RequestParam(“id”)
http://localhost/itxxzSpring4?method=listBoardTopic&id=1&userId=10&userName=tom
listBoardTopic(@RequestParam(“id”)int topicId,User user) 中的 topicId 绑定到 id 这个 URL 参数, 那么可以通过对入参使用 @RequestParam 注解来达到目的
@RequestParam(required=false):参数不是必须的,默认为true
@RequestParam(value=”id”,required=false)
请求处理方法入参的可选类型
• Java 基本数据类型和 String
默认情况下将按名称匹配的方式绑定到 URL 参数上,可以通过 @RequestParam 注解改变默认的绑定规则
• request/response/session
既可以是 Servlet API 的也可以是 Portlet API 对应的对象,Spring 会将它们绑定到Servlet 和 Portlet 容器的相应对象上
• org.springframework.web.context.request.WebRequest
内部包含了 request 对象
• java.util.Locale
绑定到 request 对应的 Locale 对象上
• java.io.InputStream/java.io.Reader
可以借此访问 request 的内容
• java.io.OutputStream / java.io.Writer
可以借此操作 response 的内容
• 任何标注了 @RequestParam 注解的入参
被标注 @RequestParam 注解的入参将绑定到特定的 request 参数上。
• java.util.Map / org.springframework.ui.ModelMap
它绑定 Spring MVC 框架中每个请求所创建的潜在的模型对象,它们可以被 Web 视图对象访问(如 JSP ) 本文来自www.itxxz.com
• 命令/ 表单对象(注:一般称绑定使用 HTTP GET 发送的 URL 参数的对象为命令对象,而称绑定使用HTTP POST 发送的 URL 参数的对象为表单对象)
它们的属性将以名称匹配的规则绑定到 URL 参数上,同时完成类型的转换。
而类型转换的规则可以通过 @InitBinder 注解或通过 HandlerAdapter 的配置进行调 整
• org.springframework.validation.Errors / org.springframework.validation.BindingResult
为属性列表中的命令/ 表单对象的校验结果,注意检验结果参数必须紧跟在命令/ 表单对象的后面
• org.springframework.web.bind.support.SessionStatus
可以通过该类型 status 对象显式结束表单的处理,这相当于触发 session 清除其中的通过@SessionAttributes 定义的属性
请求处理方法返回值的可选类型
• void
此时逻辑视图名由请求处理方法对应的 URL 确定,如以下的方法:
@RequestMapping(“/welcome.do”)
public void welcomeHandler() {}
对应的逻辑视图名为 “ welcome ”
• String
此时逻辑视图名为返回的字符,如以下的方法:
@RequestMapping(method = RequestMethod.GET)
public String setupForm(@RequestParam(“ownerId”) int ownerId, ModelMap model) {
Owner owner = this.clinic.loadOwner(ownerId);
model.addAttribute(owner);
return “ownerForm”;
}
对应的逻辑视图名为 “ ownerForm ”
• org.springframework.ui.ModelMap
和返回类型为 void 一样,逻辑视图名取决于对应请求的 URL ,如下面的例子:
@RequestMapping(“/vets.do”)
public ModelMap vetsHandler() {
return new ModelMap(this.clinic.getVets());
}
对应的逻辑视图名为 “ vets ” ,返回的 ModelMap 将被作为请求对应的模型对象,可以在 JSP 视图页面中访问到。
• ModelAndView
当然还可以是传统的 ModelAndView 。
@ModelAttribute
• 作用域:request
• 例如
@RequestMapping(“/base/userManageCooper/init.do”)
public String handleInit(@ModelAttribute(“queryBean”) ManagedUser sUser,Model model,){
• 或者
@ModelAttribute(“coopMap”)// 将coopMap 返回到页 面
public Map<Long,CooperatorInfo> coopMapItems(){}
• 说明
@ModelAttribute 声明在属性上,表示该属性的value 来源于model 里”queryBean” ,并被保存到model 里@ModelAttribute 声明在方法上,表示该方法的返回值被保存到model 里 itxxz.com
@Cacheable 和@CacheFlush
• @Cacheable :声明一个方法的返回值应该被缓 存
例如:@Cacheable(modelId = “testCaching”)
• @CacheFlush :声明一个方法是清空缓存的触发器
例如:@CacheFlush(modelId = “testCaching”)
• 说明
要配合缓存处理器使用
@Resource
• 例如
@Resource
private DataSource dataSource; // inject the bean named ‘dataSource’
• 或者
@Resource(name=”dataSource”)
@Resource(type=DataSource.class)
• 说明
@Resource 默认按bean 的name 进行查找,如果没有找到会按type 进行查找,
此时与@Autowired 类 似.
在没有为 @Resource 注解显式指定 name 属性的前提下,如果将其标注在 BeanFactory 类型、ApplicationContext 类型、ResourceLoader 类型、ApplicationEventPublisher 类型、MessageSource 类型上,那么 Spring 会自动注入这些实现类的实例,不需要额外的操作。此时 name 属性不需要指定 ( 或者指定为””),否则注入失败;
@PostConstruct 和@PreDestroy
• @PostConstruct
在方法上加上注解@PostConstruct ,这个方法就会在Bean 初始化之后被Spring 容器执 行
(注:Bean 初始化包括,实例化Bean ,并装配Bean 的属性(依赖注入))。
• @PreDestroy
在方法上加上注解@PreDestroy ,这个方法就会在Bean 被销毁前被Spring 容器执行。
@Repository
• 与@Controller 、@Service 类似,都是向spring 上下文中注册bean ,不在赘述。
@Component (不推荐使用)
@Component 是所有受Spring 管理组件的通用形式,Spring 还提供了更加细化的注解形式: @Repository 、@Service 、@Controller ,它们分别对应存储层Bean ,业务层Bean ,和展示层Bean 。
目前版本(2.5 )中,这些注解与@Component 的语义是一样的,完全通用, 在Spring 以后的版本中可能会给它们追加更多的语义。 所以,我们推荐使用@Repository 、@Service 、@Controller 来替代@Component 。
@Scope
• 例如
@Scope(“session”)
@Repository()
public class UserSessionBean implementsSerializable {}
• 说明
在使用XML 定义Bean 时,可以通过bean 的scope 属性来定义一个Bean 的作用范围,
同样可以通过@Scope 注解来完成
@Scope中可以指定如下值:
singleton:定义bean的范围为每个spring容器一个实例(默认值)
prototype:定义bean可以被多次实例化(使用一次就创建一次)
request:定义bean的范围是http请求(springMVC中有效)
session:定义bean的范围是http会话(springMVC中有效)
global-session:定义bean的范围是全局http会话(portlet中有效)
@SessionAttributes
• 说明
Spring 允许我们有选择地指定 ModelMap 中的哪些属性需要转存到 session 中,
以便下一个请求属对应的 ModelMap 的属性列表中还能访问到这些属性。
这一功能是通过类定义处标注 @SessionAttributes 注解来实现的。
@SessionAttributes 只能声明在类上,而不能声明在方法上。
• 例如
@SessionAttributes(“currUser”) // 将ModelMap 中属性名为currUser 的属性
@SessionAttributes({“attr1″,”attr2″})
@SessionAttributes(types = User.class)
@SessionAttributes(types = {User.class,Dept.class})
@SessionAttributes(types = {User.class,Dept.class},value={“attr1″,”attr2″})
@InitBinder
• 说明
如果希望某个属性编辑器仅作用于特定的 Controller ,
可以在 Controller 中定义一个标注 @InitBinder 注解的方法,
可以在该方法中向 Controller 了注册若干个属性编辑器
• 例如
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat(“yyyy-MM-dd”);
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
@Required
• 例如
@required
public setName(String name){}
• 说明 copyright www.itxxz.com
@ required 负责检查一个bean在初始化时其声明的 set方法是否被执行, 当某个被标注了 @Required 的 Setter 方法没有被调用,则 Spring 在解析的时候会抛出异常,以提醒开发者对相应属性进行设置。 @Required 注解只能标注在 Setter 方法之上。因为依赖注入的本质是检查 Setter 方法是否被调用了,而不是真的去检查属性是否赋值了以及赋了什么样的值。如果将该注解标注在非 setXxxx() 类型的方法则被忽略。
@Qualifier
• 例如
@Autowired
@Qualifier(“softService”)
private ISoftPMService softPMService;
• 说明
使用@Autowired 时,如果找到多个同一类型的bean,则会抛异常,此时可以使用 @Qualifier(“beanName”),明确指定bean的名称进行注入,此时与 @Resource指定name属性作用相同。
注解注入
注解注入顾名思义就是通过注解来实现注入, spring 和注入相关的常见注解有Autowired、Resource、Qualifier、Service、Controller、Repository、Component。
- Autowired是自动注入,自动从spring的上下文找到合适的bean来注入
- Resource用来指定名称注入
- Qualifier和Autowired配合使用,指定bean的名称
- Service,Controller,Repository分别标记类是Service层类,Controller层类,数据存储层的类,spring扫描注解配置时,会标记这些类要生成bean。
- Component是一种泛指,标记类是组件,spring扫描注解配置时,会标记这些类要生成bean。
上面的Autowired和Resource是用来修饰字段,构造函数,或者设置方法,并做注入的。而Service,Controller,Repository,Component则是用来修饰类,标记这些类要生成bean。
下面我们通过实例项目来看下spring注解注入的使用。
首先新建一个maven项目,并在pom中添加spring相关的依赖,如果不知道添加那些依赖,请参照上一篇文章。
然后新建CarDao类,给它添加@Repository注解,如下代码:
-
package cn . outofmemory . helloannotation ;
-
import org . springframework . stereotype . Repository ;
-
@Repository
-
public class CarDao {
-
public void insertCar ( String car ) {
-
String insertMsg = String . format ( “inserting car %s” , car );
-
System . out . println ( insertMsg );
-
}
-
}
新建CarService类,并给该类标注@Service注解,在这个类中定义CarDao的字段,并通过Autowired来修饰此字段,这样上面定义的CarDao类的实例就会自动注入到CarService的实例中了。
-
package cn . outofmemory . helloannotation ;
-
import org . springframework . beans . factory . annotation . Autowired ;
-
import org . springframework . stereotype . Service ;
-
@Service
-
public class CarService {
-
@Autowired
-
private CarDao carDao ;
-
public void addCar ( String car ) {
-
this . carDao . insertCar ( car );
-
}
-
}
注意:Autowired注解有一个可以为空的属性required,可以用来指定字段是否是必须的,如果是必需的,则在找不到合适的实例注入时会抛出异常。
下面我们在App. Java 中使用上面 测试 下注解注入:
-
package cn . outofmemory . helloannotation ;
-
import org . springframework . context . ApplicationContext ;
-
import org . springframework . context . annotation . AnnotationConfigApplicationContext ;
-
/**
-
* Hello world!
-
*
-
*/
-
public class App
-
{
-
public static void main ( String [] args )
-
{
-
ApplicationContext appContext = new AnnotationConfigApplicationContext ( “cn.outofmemory.helloannotation” );
-
CarService service = appContext . getBean ( CarService . class );
-
service . addCar ( “宝马” );
-
}
-
}
在上面的main方法中首先我们初始化了appContext,他是AnnotationConfigApplicationContext,它的构造函数接受一个package的名称,来限定要扫描的package。然后就可以通过appContext的getBean方法获得CarService的实例了。
上面的例子非常简单,单纯的使用AnnotationConfigApplicationContext就可以了,但是在实际项目中情况往往没有这么简单,还是需要spring配置文件的。在spring配置文件中也可以通过下面的配置让spring自动扫描注解配置。
<!-- bean annotation driven --> <context:annotation-config /> <context:component-scan base-package="cn.outofmemory.helloannotation" > </context:component-scan>
下面我们看下混合使用spring配置和注解的例子,首先在项目中添加source folder,src/main/resources,并添加spring.xml, 其内容如下:
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <!-- bean annotation driven --> <context:annotation-config /> <context:component-scan base-package="cn.outofmemory.helloannotation" > </context:component-scan> <bean id="sqliteCarDao" class="cn.outofmemory.helloannotation.CarDao" > <constructor-arg name="driver" value="sqlite"/> </bean> </beans>
在上面的配置文件中,我们通过context:annotation-config和context:component-sacn节点来指定要扫描注解注入,然后又定义了一个id为sqliteCarDao的bean,它的构造函数的driver值为sqlite。
我们修改下App.java使用xml配置文件,再运行下App看下会怎样。
-
package cn . outofmemory . helloannotation ;
-
import org . springframework . context . ApplicationContext ;
-
import org . springframework . context . annotation . AnnotationConfigApplicationContext ;
-
import org . springframework . context . support . ClassPathXmlApplicationContext ;
-
/**
-
* Hello world!
-
*
-
*/
-
public class App
-
{
-
public static void main ( String [] args )
-
{
-
ApplicationContext appContext = new ClassPathXmlApplicationContext ( “/spring.xml” );
-
CarService service = appContext . getBean ( CarService . class );
-
service . addCar ( “宝马” );
-
}
-
}
运行程序发现输出为: inserting car 宝马 into MySQL
,显然CarService自动注入的CarDao使用了默认构造函数构造的实例。是否可以通过注解指定使用spring.xml中配置的sqliteCarDao呢?
我们可以修改下CarService类,通过Qualifier注解来指定要使用的bean的名字。
如下,在指定Autowired注解时,同时指定Qualifier注解指定bean的名字
-
@Autowired
-
@Qualifier ( “sqliteCarDao” )
-
private CarDao carDao ;
重新运行下App.java 这次输出的是 inserting car 宝马 into sqlite
,这次使用了spring.xml中配置的bean了。
在文中开头我们还提到了Resouce注解,这个注解可以指定名字注入,我们再次修改下CarService类:
-
@Resource ( name = “sqliteCarDao” )
-
private CarDao carDao ;
javax.annotation.Resource注解实现的效果和@Autowired+@Qualifier的效果是一样的。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- Spring 注解编程之模式注解
- Java注解之编译时注解
- Java注解之运行时注解
- Java中的注解-自定义注解
- Java注解Annotation与自定义注解详解
- Java 元注解及 Spring 组合注解应用
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Trading and Exchanges
Larry Harris / Oxford University Press, USA / 2002-10-24 / USD 95.00
This book is about trading, the people who trade securities and contracts, the marketplaces where they trade, and the rules that govern it. Readers will learn about investors, brokers, dealers, arbit......一起来看看 《Trading and Exchanges》 这本书的介绍吧!