18点睛Spring4.1-Meta Annotation

18.1 Meta Annotation

  • 元注解:顾名思义,就是注解的注解
  • 当我们某几个注解要在多个地方重复使用的时候,写起来比较麻烦,定义一个元注解可以包含多个注解的含义,从而简化代码
  • 下面我们用<<02点睛Spring4.1-Java Config>>里的源码进行元注解的改造

18.2 示例

18.2.1 spring注解分析

我们看看spring的@Service的源码:可看出@Service注解是由几个注解组合的包含@Component;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {

    String value() default "";

}

18.2.2 自定义元注解

下面的例子不见得举得合适,但是可简单演示元注解的作用

18.2.2.1 新建元注解

组合@Configuration,@PropertySource注解为一个注解@WiselyMetaAnnotation

package com.wisely.meta;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("com/wisely/javaconfig/test.properties")
public @interface WiselyMetaAnnotation {

}
18.2.2.2 去除已有配置

去除DemoConfig上的配置,使用新定义的组合元注解

package com.wisely.meta;

import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

//@Configuration //声明是一个配置类
//@PropertySource("com/wisely/javaconfig/test.properties")
@WiselyMetaAnnotation
public class DemoConfig {

    @Bean //声明是一个bean
    public DemoService demoBean(Environment environment){
        DemoService demoService = new DemoService();
        demoService.setWord(environment.getProperty("wisely.word"));
        return demoService;
    }
}
18.2.2.3 测试
package com.wisely.meta;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
              new AnnotationConfigApplicationContext("com.wisely.meta");
        DemoService demoService = context.getBean(DemoService.class);
        System.out.println(demoService.sayHello());
        context.close();
    }

}

输出结果

Hello World

与<<02点睛Spring4.1-Java Config>>结果保持一致

 

新书推荐《JavaEE开发的颠覆者: Spring Boot实战》,涵盖Spring 4.x、Spring MVC 4.x、Spring Boot企业开发实战。

 

京东地址:http://item.jd.com/11894632.html

当当地址:http://product.dangdang.com/23926195.html

亚马逊地址:http://www.amazon.cn/图书/dp/B01D5ZBFUK/ref=zg_bsnr_663834051_6 

淘宝地址:https://item.taobao.com/item.htm?id=528426235744&ns=1&abbucket=8#detail

 

 

 

或自己在京东、淘宝、亚马逊、当当、互动出版社搜索自选。

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值