Spring中组合注解和元注解如何使用(spring,编程语言)

时间:2024-05-02 01:17:53 作者 : 石家庄SEO 分类 : 编程语言
  • TAG :

    Spring%E4%B8%AD%E7%BB%84%E5%90%88%E6%B3%A8%E8%A7%A3%E5%92%8C%E5%85%83%E6%B3%A8%E8%A7%A3%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8

一 点睛

从Spring 2开始,为了相应JDK 1.5推出的注解功能,Spring开始加入注解来替代xml配置。Spring的注解主要用来配置和注入Bean,以及AOP相关配置。随着注解的大量使用,尤其相同的多个注解用到各个类或方法中,会相当繁琐。出现了所谓的样本代码,这是Spring设计要消除的代码。

元注解:可以注解到别的注解上去的注解。

组合注解:被注解的注解,组合注解具备其上的元注解的功能。

Spring的很多注解都可以作为元注解,而且Spring本身已经有很多组合注解,如@Configuration就是一个组合了@Component的注解,表明被注解的类其实也是一个Bean。

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpublic @interface Configuration { String value() default "";}

二 实战项目

自定义一个组合注解,它的元注解是@Configuration和@ConfigurationScan

三 实战

1 自定义组合注解

package com.wisely.highlight_spring4.ch4.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 编写服务类

package com.wisely.highlight_spring4.ch4.annotation;import org.springframework.stereotype.Service;@Servicepublic class DemoService { public void outputResult(){ System.out.println("从组合注解配置照样获得的bean"); }}

3 编写配置类

package com.wisely.highlight_spring4.ch4.annotation;@WiselyConfiguration("com.wisely.highlight_spring4.ch4.annotation")public class DemoConfig {}

4 编写主类

package com.wisely.highlight_spring4.ch4.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(); }}

本文:Spring中组合注解和元注解如何使用的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:如何实现springbootweb项目打jar或者war包并运行下一篇:

4 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18