- @Configuration
- @EnableWebMvc
- @ComponentScan(basePackages = { "com.apress.prospringmvc.bookstore.web" })
- public class WebMvcContextConfiguration extends WebMvcConfigurerAdapter {
- @Override
- public void addViewControllers(final ViewControllerRegistry registry) {
- registry.addViewController("/index.htm").setViewName("index");
- }
- }
@Configuration 和@ComponentScan注解背后会做什么呢?
@ComponentScan
其实很简单,@ComponentScan告诉Spring 哪个packages 的用注解标识的类 会被spring自动扫描并且装入bean容器。
例如,如果你有个类用@Controller注解标识了,那么,如果不加上@ComponentScan,自动扫描该controller,那么该Controller就不会被spring扫描到,更不会装入spring容器中,因此你配置的这个Controller也没有意义。
类上的注解@Configuration 是最新的用注解配置spring,也就是说这是个配置文件,和原来xml配置是等效的,只不过现在用java代码进行配置了 加上一个@Configuration注解就行了,是不是很方便,不需要那么繁琐的xml配置了,这样基于注解的配置,可读性也大大增高了。
@Target:注解的作用目标
@Target(ElementType.TYPE)
//
接口、类、枚举、注解
@Target(ElementType.FIELD)
//
字段、枚举的常量
@Target(ElementType.METHOD)
//
方法
@Target(ElementType.PARAMETER)
//
方法参数
@Target(ElementType.CONSTRUCTOR)
//
构造函数
@Target(ElementType.LOCAL_VARIABLE)
//
局部变量
@Target(ElementType.ANNOTATION_TYPE)
//
注解
@Target(ElementType.PACKAGE) /
//
包
@Retention(RetentionPolicy.RUNTIME)
@Retention:注解的保留位置
@Retention(RetentionPolicy.SOURCE)
//注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS)
// 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@Retention(RetentionPolicy.RUNTIME)
// 注解会在class字节码文件中存在,在运行时可以通过反射获取到
@Document:说明该注解将被包含在javadoc中
@Inherited:说明子类可以继承父类中的该注解
举例:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface AnnatDemo{
public int value();
}
@Target({ElementType.METHOD})
public @interface AnnatDemo{
public int value();
}
以上代码定义了@AnnatDemo注解,作用目标是 用于对方法注解,并且保留在运行时的环境中,我们可以利用反射 获得一个方法上的注解 调用定义的方法,
比如@AnnatDemo 作用于以下方法:
public interface IClientProtocolEx extends IProtocol {
int METHOD_START=0;
@AnnatDemo(METHOD_START)
public String say(String person);
public String say(String person);
}
那么可以利用以下代码进行反射:
Class ipt=IClientProtocalEx.class;
Method[] mts=ipt.getMethod();
for(Method mt:mts)
{
AnnatDemo ad=mt.getAnnotation(AnnatDemo.class);//如果方法上 没有该注解 则返回null
int value=ad.value();
System.out.println("value:"+value);
}
注解是用于建设基础jar包的一部分 项目都有自己的框架,若运用恰当,注解则为其中良好的一部分!
-------------------------------------------------------------------------------------
参考:http://blog.youkuaiyun.com/zsq520520/article/details/55261359
更多注解 请查看上面链接