1. 程式人生 > >spring自定義註解的簡單使用案例+ApplicationContextAware介面的使用

spring自定義註解的簡單使用案例+ApplicationContextAware介面的使用

  程式碼

註解

@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();
			}
		}
	}

}

 配置和專案截圖

 

 

結果: