添加组件

@Configuration、@Bean

//以swagger为例
@Configuration(proxyBeanMethods = false)
@EnableSwagger2 //使用swagger注解
public class SwaggerConfig { @Bean
public Docket webApiConfig(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("webApi")
.apiInfo(webApiInfo())
.select()
//.paths(Predicates.not(PathSelectors.regex("/admin/.*")))
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build(); }
}
  • @Configuration:告诉SpringBoot这是一个配置类 ,即配置文件,配置类也是组件

  • @Bean:添加组件。返回类型就是组件类型。返回值就是组件在容器中的实例,可以自定义组件名,默认组件名为方法名

proxyBeanMethods参数

  • true:full模式,表示通过@Bean注册的组件是单实例的,也是默认值。配置类中注册的组件每次被调用时,都会检查

    容器中是否已经存在该组件,若存在就不重新创建

  • false:lite模式,表示组件无论被调用多少次返回的组件都是新创建的,关闭了检查机制,组件每次被调用时都是重新创建

@Configuration(proxyBeanMethods = false)
public class MyConfig {
/*
给容器中添加组件。
以方法名作为组件的id。
返回类型是组件类型,返回值就是组件在容器中的实例
*/
@Bean
public User getUser(){
User lixiang = new User("莉香", 18);
//user组件依赖了Pet组件
lixiang.setPet(getPet());
return lixiang;
} @Bean
public Pet getPet(){
Pet pet = new Pet("哈士奇");
return pet;
}
}
@SpringBootApplication
public class Springboot01Application { public static void main(String[] args) {
//1、返回IOC容器
ConfigurableApplicationContext run = SpringApplication.run(Springboot01Application.class, args); //2、查看IOC容器里的组件
String[] names = run.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
} //3、从容器中获取组件
MyConfig bean = run.getBean(MyConfig.class);
User user1 = bean.getUser();
User user2 = bean.getUser(); //User(userName=莉香, age=18, pet=Pet(name=哈士奇, weight=null))
System.out.println(user1); //org.springframework.aop.config.internalAutoProxyCreator,配置类是一个代理对象
System.out.println(bean); //4、测试proxyBeanMethods,默认开启
System.out.println(user1 == user2); //false Pet pet = run.getBean("getPet", Pet.class);
System.out.println("是否是同一个宠物:"+ (user1.getPet() == pet)); //是否是同一个宠物:false
} }

说明

  • 配置类的组件之间无依赖关系Lite模式加速容器启动过程,减少判断
  • 有依赖关系,用Full模式(默认),得到之前单实例组件,

@Bean、@Component、@Controller、@Service、@Repository

它们是Spring的基本标签,在Spring Boot中并未改变它们原来的功能

  • @Bean:初始化一个Spring IOC容器管理的新对象。
  • @Component: 被注解的类会自动被添加进Spring容器中
  • @Repository: 用于持久层
  • @Service: 表示被注解的类是位于业务层的业务组件。
  • @Controller :用于标注控制层
  • 以上组件的功能起始都是给IOC容器中注册组件,只是应用的场景不同
  • 只有组件在容器中才能访问容器中的其他组件,这也是为什么实现类要加@Service@component,因为实现类经常要使用@Autowired自动装配其他组件

@ComponentScan

public @interface ComponentScan {
@AliasFor("basePackages")
String[] value() default {}; @AliasFor("value")
String[] basePackages() default {}; ...
}
  • 启动类注解@SpringBootApplication的组合属性之一
  • @ComponentScan的功能其实就是自动扫描加载符合条件的组件(@Component,@Service,@Repository)或者用@Bean修饰加入到IOC容器中的组件
  • 我们可以通过basePackages属性定制@ComponentScan自动扫描的范围,如果不指定,则默认会从启动类所在包开始向下扫描

@Import

顾名思义,将已存在的类导入到IOC容器中

@Import({User.class, DBHelper.class})//给容器中自动创建出这两个类型的组件
@Configuration(proxyBeanMethods = false)
public class MyConfig {
}

@Conditional条件装配

满足Conditional指定的条件,则进行注入

F4打开继承结构,可以看到有很多判断条件,springboot底层使用该注解的地方很多,可自行了解

@ImportResource

原生配置文件引入:若项目中有用原先xml方式的配置文件,spring容器是获取不到配置文件的数据的,在配置类中加入该注解就可以获取xml文件配置的组件

<!--======================beans.xml=========================-->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <bean id="haha" class="com.atguigu.boot.bean.User">
<property name="name" value="zhangsan"></property>
<property name="age" value="18"></property>
</bean> <bean id="hehe" class="com.atguigu.boot.bean.Pet">
<property name="name" value="tomcat"></property>
</bean>
</beans>
@Configuration
@ImportResource("classpath:beans.xml")
public class MyConfig { }

配置绑定

@ConfigurationProperties + @Component

读取到properties文件中的内容,并且把它封装到实体类中

@Data
@ToString
@Component //注册进容器中
@ConfigurationProperties(prefix = "mycar") //获取前缀带有mycar的配置
public class Car { private String brand; private Integer price;
}

类的属性必须有getset方法

#application.properties
mycar.brand=BYD
mycar.price=10000

@ConfigurationProperties只能给注册进容器的组件绑定配置,但有时调用的是第三方接口,若接口方实体类进容器,@ConfigurationProperties就无法使用,这时就要用到另一个注解

@EnableConfigurationProperties + @ConfigurationProperties

@EnableConfigurationProperties:获取配置文件的属性值同时会将实体类加入容器中

@Configuration
@EnableConfigurationProperties({Car.class})
public class MyConfig { }

@EnableConfigurationProperties的参数是数组形式,参数只有一个值时可以不加{},有多个参数时要加{},并用,隔开

//此时可以不加@Component
@Data
//@Component
@ConfigurationProperties(prefix = "mycar") //获取前缀带有mycar的配置
public class Car { private String brand; private Integer price;
}

springboot注解之容器功能的更多相关文章

  1. springboot注解大全

    springboot注解:@Service: 注解在类上,表示这是一个业务层bean@Controller:注解在类上,表示这是一个控制层bean@Repository: 注解在类上,表示这是一个数据 ...

  2. 【转载】springboot注解

    https://blog.csdn.net/yitian_66/article/details/80866571 springboot注解:@Service: 注解在类上,表示这是一个业务层bean@ ...

  3. SPRINGBOOT注解最全详解(

    #     SPRINGBOOT注解最全详解(整合超详细版本)          使用注解的优势:               1.采用纯java代码,不在需要配置繁杂的xml文件           ...

  4. springboot注解之@Import @Conditional @ImportResource @ConfigurationProperties @EnableConfigurationProperties

    1.包结构 2.主程序类 1 @SpringBootApplication(scanBasePackages={"com.atguigu"}) 2 public class Mai ...

  5. SpringBoot切换Tomcat容器,SpringBoot使用Jetty容器

    SpringBoot切换Tomcat容器, SpringBoot修改为Jetty容器, SpringBoot使用undertow容器, SpringBoot使用Jetty容器 ============ ...

  6. 转-spring-boot 注解配置mybatis+druid(新手上路)-http://blog.csdn.net/sinat_36203615/article/details/53759935

    spring-boot 注解配置mybatis+druid(新手上路) 转载 2016年12月20日 10:17:17 标签: sprinb-boot / mybatis / druid 10475 ...

  7. Springboot关于tomcat容器配置、三大组件配置、拦截器配置

    原文地址:http://www.javayihao.top/detail/172 1.tomcat配置 Springboot默认使用的就是嵌入式servlet容器即tomcat,对于web项目,如果使 ...

  8. springboot + 注解 + 拦截器 + JWT 实现角色权限控制

    1.关于JWT,参考: (1)10分钟了解JSON Web令牌(JWT) (2)认识JWT (3)基于jwt的token验证 2.JWT的JAVA实现 Java中对JWT的支持可以考虑使用JJWT开源 ...

  9. 【Spring注解驱动开发】使用@Import注解给容器中快速导入一个组件

    写在前面 我们可以将一些bean组件交由Spring管理,并且Spring支持单实例bean和多实例bean.我们自己写的类,可以通过包扫描+标注注解(@Controller.@Servcie.@Re ...

随机推荐

  1. vue 熟悉项目结构 创建第一个自己的组件

    * vue开发环境搭建 * 项目入口文件 ./src/main.js // The Vue build version to load with the `import` command // (ru ...

  2. Wannafly挑战赛10F-小H和遗迹【Trie,树状数组】

    正题 题目链接:https://ac.nowcoder.com/acm/contest/72/F 题目大意 \(n\)个字符串,包括小写字母和\(\#\).其中\(\#\)可以替换为任意字符串.求有多 ...

  3. Windows下node-gyp查找VS安装路径简单解析

    node-gyp的作用我已经不想赘述了,这里给一个我之前文章的链接:cnblogs看这里,知乎看这里.本文主要从源码入手,介绍node-gyp查找VisualStudio的过程 为了方便我们研究nod ...

  4. 重磅 | 阿里开源首个 Serverless 开发者平台 Serverless Devs

    Serverless 从概念提出到应用,已经走过了 8 个年头,开发者对 Serverless 的使用热情不断高涨.为帮助开发者实现一键体验多云产品,极速部署 Serverless 项目,10 月 2 ...

  5. zabbix和prometheus的优缺点对比

    使用Prometheus(https://github.com/prometheus)原生的k8s服务发现驱动,采集容器化信息:通过微服务参数配置,暴露运行状态信息提供给prometheus,实现微服 ...

  6. 2020.11.6-vj补题

    A - A CodeForces - 136A 题解:按输入的顺序输出对应的下标即可,定义一个数组,将输入的作为下标,下标为值,最后依次输出即可: #include<bits/stdc++.h& ...

  7. Fikker 管理平台弱口令

    官网:www.fikker.com 应用介绍:Fikker 是一款面向 CDN/站长 的专业级网站缓存(Webcache)和反向代理服务器软件(Reverse Proxy Server). 发现过程: ...

  8. Gitlab Burndown Chart

    一.说明 通过调用gitlab api直接获取相应project的所有issues,然后对其进行统计以制作燃尽图 二.方法 1.生成 Personal access token Gitlab > ...

  9. OO_JAVA_JML系列作业_单元总结

    OO_JAVA_JML系列作业_单元总结 (1)梳理JML语言的理论基础.应用工具链情况 简单梳理 以下三者是jml规格里的核心,对一个方法功能和属性的限制: requires子句:规定方法的前置条件 ...

  10. 热身训练1 ping ping ping

    点此进入 题意: 一棵树,n+1 个节点,以0号节点为根,给出端点(a,b),节点a到节点b的路径上,至少有一个点是"坏掉的",求"坏掉的点"最少 分析: St ...