spring自定义注解的简单使用案例+ApplicationContextAware接口的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhou920786312/article/details/85225679

  代码

注解

@Target({ ElementType.TYPE })//注解用在接口上
@Retention(RetentionPolicy.RUNTIME)//VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息
@Component
public @interface RpcService {
	String value();
}


-----
使用注解

public interface HelloService {
    String hello(String name);
}

@RpcService("你好啊")
public class HelloServiceImpl implements HelloService {
    public String hello(String name) {
        return  name;
    }
    
}

测试类


@Component        //ApplicationContextAware会为Component组件调用setApplicationContext方法;  测试Myserver3时注释
public class Test implements ApplicationContextAware {
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring2.xml");
	}


	public void setApplicationContext(ApplicationContext ctx)throws BeansException {
			
		//获取被注解标准的bean
		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, "hello world");
				System.out.println("hello方法的返回值:"+invoke.toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}

 配置和项目截图

结果:

猜你喜欢

转载自blog.csdn.net/zhou920786312/article/details/85225679