直接上代码比较容易理解。
RpcService.java
package com.mrbcy.bigdata.basic.spring.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.stereotype.Component;
@Target({ ElementType.TYPE })//注解用在接口上
@Retention(RetentionPolicy.RUNTIME)//VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息
@Component
public @interface RpcService {
String value();
}
HelloService.java
package com.mrbcy.bigdata.basic.spring.annotation;
public interface HelloService {
String hello(String name);
}
HelloServiceImpl.java
package com.mrbcy.bigdata.basic.spring.annotation;
@RpcService("HelloServicebb")
public class HelloServiceImpl implements HelloService {
public String hello(String name) {
return "Hello! " + name;
}
public void test(){
System.out.println("test");
}
}
MyServer.java
package com.mrbcy.bigdata.basic.spring.annotation;
import java.lang.reflect.Method;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
@Component //ApplicationContextAware会为Component组件调用setApplicationContext方法; 测试Myserver3时注释
public class MyServer implements ApplicationContextAware {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext2.xml");
}
public void setApplicationContext(ApplicationContext ctx)
throws BeansException {
Map<String, Object> serviceBeanMap = ctx
.getBeansWithAnnotation(RpcService.class);
for (Object serviceBean : serviceBeanMap.values()) {
try {
//获取自定义注解上的value
String value = serviceBean.getClass().getAnnotation(RpcService.class).value();
System.out.println("注解上的value: " + value);
//反射被注解类,并调用指定方法
Method method = serviceBean.getClass().getMethod("hello",
new Class[] { String.class });
Object invoke = method.invoke(serviceBean, "bbb");
System.out.println(invoke);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
applicationContext2.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">
<context:component-scan base-package="com.mrbcy.bigdata.basic.spring.annotation"/>
</beans>
执行结果:
注解上的value: HelloServicebb
Hello! bbb
可以看出Spring框架拿到了使用了我们自定义注解的类然后成功调用了它的成员函数。