spring boot2.x ——注解

背景

从Sring2 开始,为了响应JDK1.5退出的注解功能,Spring 开始大量假如注解来代替xml配置。Spring 的注解主要用来配置注入Bean,切面相关的配置(@Transactional)。随着Spring版本的不断迭代更新,注解被大量使用。越来越多的自定义注解也出现在自己的项目中来提供便捷配置。

1、组合注解与元注解

  • 解释
    • 组合注解
      • 被注解的注解称之为组合注解
      • 组合注解具备元注解的功能
      • spring 本身也有很多组合注解,比如:@Configuration 就是一个组合@Component注解,表明这个类其实也是一个Bean
    • 元注解
      • 可以注解到别的注解上的注解
      • spring 的很多注解都可以作为元注解
      • @Target(ElementType.TYPE)
        @Retention(RetentionPolicy.RUNTIME)
        @Documented
  • 示例
    • (1) 组合注解
package com.tsshare.srcspringbootexampletsshare.day1.annotation;

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

import java.lang.annotation.*;

/**
 * @author guabei
 * @title: Compose
 * @projectName spring-boot-build
 * @description: 自定义组合注解
 * @date 2020/1/823:03
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration //<1>
@ComponentScan //<2>
public @interface ComposeConfigAndCompScan {
	//<3>
	String[] value() default {};
}
  • <1> 组合 @Configuration 元注解
  • <2> 组合 @ComponentScan 元注解
  • <3> 覆盖value 参数
  • (2) 演示服务的Bean
package com.tsshare.srcspringbootexampletsshare.day1.service;

import org.springframework.stereotype.Service;

/**
 * @author guabei
 * @title: DemoService
 * @projectName spring-boot-build
 * @description: 实例bean
 * @date 2020/1/823:30
 */
@Service
public class DemoService {

	public void demoOutPut(){
		System.out.println("从组合注解配置照样获得的Bean");
	}
}

  • (3) 新的配置类
package com.tsshare.srcspringbootexampletsshare.day1;

import com.tsshare.srcspringbootexampletsshare.day1.annotation.ComposeConfigAndCompScan;

/**
 * @author guabei
 * @title: DemoConfig
 * @projectName spring-boot-build
 * @description: 配置注解的示例
 * @date 2020/1/823:51
 */
@ComposeConfigAndCompScan(value = {"com.tsshare.srcspringbootexampletsshare.day1"}) //<1>
public class DemoAnnoConfig {
}
  * <1> 使用@ComposeConfigAndCompScan 组合代替@Configuration + @ComponentScan
  • (4) 运行
package com.tsshare.srcspringbootexampletsshare.day1;

import com.tsshare.srcspringbootexampletsshare.day1.DemoAnnoConfig;
import com.tsshare.srcspringbootexampletsshare.day1.service.DemoService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author chenzhenfei
 * @title: AnnoMain
 * @projectName spring-boot-build
 * @description: 测试
 * @date 2020/1/823:40
 */

public class AnnoMain {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context =new AnnotationConfigApplicationContext(DemoAnnoConfig.class);
		DemoService demoService =context.getBean(DemoService.class);
		demoService.demoOutPut();
		context.close();
	}
}

* 结果显示

在这里插入图片描述

2、条件注解@Conditional

  • 2.1 解释
    @Conditional 根据满足某一特定条件创建一个特定的Bean,比方说,当某一个jar包在一个类路径下的时候,自动配置一个或者多个Bean;或者只有某个Bean 被创建才会创建两外一个Bean。总的来说,就是根据特定条件来控制Bean的创建行为,这样我们可以利用这个特性进行一些自动配置。在spring boot 中将会大量应用到条件注解,下面将演示一个@Conditional 的示例来向大家暂时其作用
  • 2.2 示例
    1 、判断条件定义 建立项目
    在这里插入图片描述
    (1) 判断windows 的条件
package com.tsshare.srcspringbootexampletsshare.day2.define;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

/**
 * @author guabei
 * @title: WindowCondition
 * @projectName spring-boot-build
 * @description: window 条件定义
 * @date 2020/1/90:25
 */
public class WindowCondition implements Condition {
	@Override
	public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
		return context.getEnvironment().getProperty("os.name").contains("Windows");
	}
}

(2) 判断linux的条件

package com.tsshare.srcspringbootexampletsshare.day2.define;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

/**
 * @author guabei
 * @title: WindowCondition
 * @projectName spring-boot-build
 * @description: linux 条件定义
 * @date 2020/1/90:25
 */
public class LinuxCondition implements Condition {
	@Override
	public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
		return context.getEnvironment().getProperty("os.name").contains("Linux");
	}
}

2 、 定义不同系统下的配置Bean 的实体类

(1) 接口

package com.tsshare.srcspringbootexampletsshare.day2.service;

/**
 * @author guabei
 * @title: ListService
 * @projectName spring-boot-build
 * @description: 接口案例
 * @date 2020/1/90:29
 */
public interface ListService {
	String showListCmd();
}

(2)window 所要创建Bean 类

package com.tsshare.srcspringbootexampletsshare.day2.service.impl;

import com.tsshare.srcspringbootexampletsshare.day2.service.ListService;

/**
 * @author guabei
 * @title: WindowListService
 * @projectName spring-boot-build
 * @description: WindowListService
 * @date 2020/1/90:30
 */
public class WindowListService implements ListService {
	@Override
	public String showListCmd() {
		return "Windows - dir";
	}
}

(2)linux 所要创建Bean 类

package com.tsshare.srcspringbootexampletsshare.day2.service.impl;

import com.tsshare.srcspringbootexampletsshare.day2.service.ListService;

/**
 * @author guabei
 * @title: WindowListService
 * @projectName spring-boot-build
 * @description: WindowListService
 * @date 2020/1/90:30
 */
public class LinuxListService implements ListService {
	@Override
	public String showListCmd() {
		return "Linux - ls";
	}
}

3、配置生成Bean 的类


```java
package com.tsshare.srcspringbootexampletsshare.day2.config;

import com.tsshare.srcspringbootexampletsshare.day2.define.LinuxCondition;
import com.tsshare.srcspringbootexampletsshare.day2.define.WindowCondition;
import com.tsshare.srcspringbootexampletsshare.day2.service.ListService;
import com.tsshare.srcspringbootexampletsshare.day2.service.impl.LinuxListService;
import com.tsshare.srcspringbootexampletsshare.day2.service.impl.WindowListService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

/**
 * @author guabei
 * @title: ConditionConfig
 * @projectName spring-boot-build
 * @description: TODO
 * @date 2020/1/90:32
 */
@Configuration
public class ConditionConfig {
	@Bean
	/**
	 * <1>
	 */
	@Conditional(WindowCondition.class)
	public ListService windowListService(){
		return new WindowListService();
	}
	@Bean
	/**
	 * <2>
	 */
	@Conditional(LinuxCondition.class)
	public ListService LinuxListService(){
		return new LinuxListService();
	}

}

  • <1> 通过@Conditional 注解,符合WindowCondition条件则实例化WindowListService;
  • <2> 通过@Conditional 注解,符合LinuxCondition条件则实例化LinuxListService;

4、运行测试

package com.tsshare.srcspringbootexampletsshare.day2;

import com.tsshare.srcspringbootexampletsshare.day1.DemoAnnoConfig;
import com.tsshare.srcspringbootexampletsshare.day1.service.DemoService;
import com.tsshare.srcspringbootexampletsshare.day2.config.ConditionConfig;
import com.tsshare.srcspringbootexampletsshare.day2.service.ListService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ConditionContext;

/**
 * @author guabei
 * @title: AnnoMain
 * @projectName spring-boot-build
 * @description: 测试
 * @date 2020/1/823:40
 */

public class ConditionAnnoMain {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context =new AnnotationConfigApplicationContext(ConditionConfig.class);
		ListService demoService =context.getBean(ListService.class);
		String out = demoService.showListCmd();
		System.out.println(context.getEnvironment().getProperty("os.name")+" 系统下的列表命令为:" +out);
		context.close();
	}
}

5、输出结果如图
在这里插入图片描述
6、后续复杂类型的注解可以以上分析方式去了解他的实现逻辑。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在个人博客系统中,拓展模块是非常重要的,因为它可以提供给用户更多的功能和服务。在本文中,我们将介绍如何在 Spring Boot 项目中实现一个拓展模块。 首先,我们需要先定义一个接口,用于规范拓展模块的实现: ```java public interface BlogModule { String moduleName(); // 获取模块名称 void start(); // 模块启动方法 void stop(); // 模块停止方法 List<String> addPage(String pageName); // 增加页面 } ``` 接下来,我们需要创建一个基础的拓展模块,作为其他拓展模块的基类: ```java public abstract class BaseBlogModule implements BlogModule { private String moduleName; public BaseBlogModule(String moduleName) { this.moduleName = moduleName; } @Override public String moduleName() { return moduleName; } } ``` 在基类中,我们实现了 `moduleName()` 方法,返回拓展模块的名称,并在构造函数中初始化了名称。 然后,我们可以开始实现具体的拓展模块了。假设我们需要实现一个功能,可以在博客系统中添加页面。我们可以创建一个名为 `AddPageModule` 的拓展模块: ```java public class AddPageModule extends BaseBlogModule { private List<String> pages = new ArrayList<>(); public AddPageModule() { super("AddPageModule"); } @Override public void start() { System.out.println("AddPageModule starting..."); } @Override public void stop() { System.out.println("AddPageModule stopping..."); } @Override public List<String> addPage(String pageName) { pages.add(pageName); return pages; } } ``` 在这个拓展模块中,我们实现了 `start()` 和 `stop()` 方法,用于在模块启动和停止时执行一些操作。同时,我们还实现了 `addPage()` 方法,用于添加页面,并返回当前系统中所有的页面。 最后,我们需要在 Spring Boot 项目中将这个拓展模块注入到容器中,并在需要的地方调用它的方法。我们可以使用 `@Autowired` 注解将拓展模块注入到其他组件中: ```java @Service public class BlogService { @Autowired private List<BlogModule> modules; public List<String> addPage(String pageName) { List<String> pages = new ArrayList<>(); for (BlogModule module : modules) { pages.addAll(module.addPage(pageName)); } return pages; } } ``` 在这个示例中,我们使用 `@Autowired` 注解将 `BlogModule` 的实现类自动注入到 `modules` 列表中,并在 `addPage()` 方法中循环遍历所有的模块,调用它们的 `addPage()` 方法。 通过这种方式,我们可以轻松地实现一个可拓展的 Spring Boot 项目,并在需要的时候动态地增加或删除拓展模块。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值