除了使用xml文件配置外,从spring 3.0开始还提供了使用注解进行配置。
使用注解进行配置,可以简化繁琐的xml配置,将上例的HelloWorld修改为注解配置。
首先我们看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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" >
<!--该标签作用为扫描并自动为添加了相应注释的类注册Bean-->
<context:component-scan base-package="com.example.assembly"></context:component-scan>
</beans>
可以看到,现在的xml文件已经没有手动配置的Bean了,除了Spring的配置文件头部,只有一个context:component-scan标签,该标签表示IoC容器自动检测包下的类,并为添加了对应注释的Bean进行注册。
类文件变为:
package com.example.assembly;
import org.springframework.stereotype.Component;
@Component("hello")
public class assemblytest {
private String name;
public assemblytest(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public void say() {
System.out.println(name+" say:"+"Hello World"+this.hashCode());
}
}
仅仅是在类上添加了一个注解@Component,相当于告诉IoC容器扫描到时需要为这个类注册Bean。
运行结果和之前相同。
这样就大大简化了Bean的配置,常用的注解还有很多,在此仅以一个简单的例子抛砖引玉。