Spring Boot实战(三)Spring高级话题 3.5组合注解与元注解

从Spring 2开始,为了响应JDK1.5推出的注解功能,Spring开始大量加入注解来替代xml配置。Spring的注解主要用来配置和注入Bean,以及AOP相关配置(@Transactional)。随着注解的大量使用,尤其相同的多个注解用到各个类或方法中,会相当繁琐。这就是所谓的样板代码(boilerplate code),是Spring设计原则中要消除的代码。
所谓元注解其实就是可以注解到别的注解上的注解,被注解的注解称之为组合注解,组合注解具备注解其上的元注解的功能。Spring的很多注解都可以作为元注解,而且Spring本身已经有很多组合注解,如@Configuration就是一个组合@Component注解,表明这个类其实也是一个Bean。
我们前面的章节里大量使用@Configuration和@ComponentScan注解到配置类上,如果你跟着本文一直在敲代码的话是不是觉得已经有点麻烦了呢?下面我将这两个元注解组合成一个组合注解,这样我们只需写一个注解就可以表示两个注解。
3.5.2 示例
(1)示例组合注解。

package com.wisely.highlight_spring4.ch3.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

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

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration  //组合Configuration元注解
@ComponentScan  //组合ComponentScan元注解
public @interface WiselyConfiguration {
	String [] value () default {} ; //覆盖value参数。 
}

(2)演示服务Bean。

package com.wisely.highlight_spring4.ch3.annotation;

import org.springframework.stereotype.Service;

@Service
public class DemoService {
	public void outputResult(){
		System.out.println("从组合注解配置照样获得的bean");
	}
}

(3)新的配置类。

package com.wisely.highlight_spring4.ch3.annotation;

@WiselyConfiguration("com.wisely.highlight_spring4.ch3.annotation")//使用@WiselyConfiguration组合注解替代@Configuration和@ComponentScan
public class DemoConfig {
	
}

(4)运行。

package com.wisely.highlight_spring4.ch3.annotation;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = 
				new AnnotationConfigApplicationContext(DemoConfig.class);
		
		DemoService demoService = context.getBean(DemoService.class);
		
		demoService.outputResult();
		
		context.close();
	}
}

在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值