栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring的组合注解和元注解原理与用法详解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring的组合注解和元注解原理与用法详解

本文实例讲述了Spring的组合注解和元注解原理与用法。分享给大家供大家参考,具体如下:

一 点睛

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

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

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

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

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@documented
@Component
public @interface Configuration {
  String value() default "";
}

二 实战项目

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

三 实战

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 编写服务类

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

四 运行

从组合注解配置照样获得的bean

更多关于java相关内容感兴趣的读者可查看本站专题:《Spring框架入门与进阶教程》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/136321.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号