【Spring】自定义注解
bean的初始化顺序
- spring先检查注解注入的bean,并将它们实例化。
- spring初始化bean的顺序是按照applicationContext.xml中配置的顺序依次执行构造。
- 如果某个类实现了ApplicationContextAware接口,会在类初始化完成后调用setApplicationContext()方法进行操作。
- 如果某个类实现了InitializingBean接口,会在类初始化完成后,并在setApplicationContext()方法执行完毕后,调用afterPropertiesSet()方法进行操作。
Spring注解的使用
- 在spring中,用注解来向Spring容器注册Bean。需要在applicationContext.xml中注册
<context:component-scan base-package=”pagkage1[,pagkage2,…,pagkageN]”/>
。 - 如果某个类的头上带有特定的注解
@Component/@Repository/@Service/@Controller
,就会将这个对象作为Bean注册进Spring容器。 - 在使用spring管理的bean时,无需在对调用的对象进行new的过程,只需使用@Autowired将需要的bean注入本类即可。
Spring自定义注解
作用
在反射中获取注解,以取得注解修饰的类、方法、属性的相关解释。
Java内置注解
@Target
表示该注解用于什么地方,可能的ElemenetType参数包括:
ElemenetType.CONSTRUCTOR
:构造器声明。ElemenetType.FIELD
:域声明(包括enum实例)。ElemenetType.LOCAL_VARIABLE
:局部变量声明。ElemenetType.METHOD
:方法声明。ElemenetType.PACKAGE
:包声明。ElemenetType.PARAMETER
:参数声明。ElemenetType.TYPE
:类,接口(包括注解类型)或enum
声明。
@Retention
表示在什么级别保存该注解信息,可选的RetentionPolicy参数包括:
RetentionPolicy.SOURCE
:注解将被编译器丢弃。RetentionPolicy.CLASS
:注解在class文件中可用,但会被JVM丢弃。RetentionPolicy.RUNTIME
:JVM将在运行期也保留注释,因此可以通过反射机制读取注解的信息。
使用
- 定义自定义注解
/**
* 自定义注解
* @author dj4817
* @version $Id: RpcService.java, v 0.1 2017/12/10 20:30 dj4817 Exp $$
*/
// 注解用在接口上
@Target({ ElementType.TYPE })
// JVM将在运行期也保留注释,因此可以通过反射机制读取注解的信息
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface RpcService {
String value();
}
- 将自定义注解加到需要使用的类上,这样我们就可以通过获取注解,来得到这个类。
/**
* 业务实现类
* @author dj4817
* @version $Id: HelloServiceImpl.java, v 0.1 2017/12/10 20:34 dj4817 Exp $$
*/
@RpcService("helloService")
public class HelloServiceImpl implements HelloService {
/**
* hello方法
* @param name
* @return
*/
@Override
public String hello(String name) {
return "hello:" + name;
}
}
- 通过ApplicationContext可以获取所有标记这个注解的类
/**
* 测试自定义注解获取
* @author dj4817
* @version $Id: MyServer.java, v 0.1 2017/12/10 20:37 dj4817 Exp $$
*/
@Component
public class MyServer implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
// 从spring上下文中获取RpcService注解的bean
Map<String, Object> serviceBeans = applicationContext.getBeansWithAnnotation(RpcService.class);
for (Object serviceBean : serviceBeans.values()) {
try {
// 获取自定义注解上的value
String value = serviceBean.getClass().getAnnotation(RpcService.class).value();
System.out.println("注解上的value: " + value);
// 反射被注解类,并调用指定方法
Method method = serviceBean.getClass().getMethod("hello", String.class);
Object invoke = method.invoke(serviceBean, "david");
System.out.println(invoke);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
评论区