1.容器组件的添加:
1.@Configuration
在之前没有使用Springboot的时候,如果是给IOC容器中添加组件的话,就需要在Spring的配置文件中添加Bean标签,然后添加组件
但是在springboot中,就尅不用使用配置文件
可以自己写一个MyConfig类,使用注解
@Configuration//告诉SpringBoot这是一个配置类,就相当于配置文件。
就可以向容器中添加组件了。
基本使用
Full模式与Lite模式
示例
最佳实战:
- 配置 类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断
- 配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式
#############################Configuration使用示例######################################################
/**
* 1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
* 2、配置类本身也是组件
* 3、proxyBeanMethods:代理bean的方法
* Full(proxyBeanMethods = true)、【保证每个@Bean方法被调用多少次返回的组件都是单实例的】
* Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】
* 如果是组件依赖必须使用Full模式默认。其他默认是Lite模式
*
*
*
*/
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
public class MyConfig {
/**
* Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
* @return
*/
@Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
public User user01(){
User zhangsan = new User("zhangsan", 18);
//user组件依赖了Pet组件
zhangsan.setPet(tomcatPet());
return zhangsan;
}
@Bean("tom")
public Pet tomcatPet(){
return new Pet("tomcat");
}
}
################################@Configuration测试代码如下########################################
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.lsy.boot")
public class MainApplication {
public static void main(String[] args) {
//1、返回我们IOC容器
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
//2、查看容器里面的组件
String[] names = run.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}
//3、从容器中获取组件
Pet tom01 = run.getBean("tom", Pet.class);
Pet tom02 = run.getBean("tom", Pet.class);
System.out.println("组件:"+(tom01 == tom02));//true
//配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
MyConfig bean = run.getBean(MyConfig.class);
System.out.println(bean);//也是一个单实例的
//如果@Configuration(proxyBeanMethods = true)代理对象调用方法。SpringBoot总会检查这个组件是否在容器中有。
//保持组件单实例
User user = bean.user01();
User user1 = bean.user01();
System.out.println(user == user1);//true,
//说明这两个实例是相同的,直接在容器中获取的
User user01 = run.getBean("user01", User.class);
Pet tom = run.getBean("tom", Pet.class);
System.out.println("用户的宠物:"+(user01.getPet() == tom));
//如果是Full模式的话,因为是组件依赖,所以使用Full模式,则user01.getPet() == tom返回的是true
//如果是Lite模式的话,返回的就是False,每次都会重新创建一个。
}
}
可以看到容器中的组件:
2.@Bean、@Component、@Controller、@Service、@Repository(也是给容器中添加组件)
3、@ComponentScan组件的扫描
4.@Import
@Import({User.class, DBHelper.class}) 给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
* 4、@Import({User.class, DBHelper.class})
* 给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
*
*
*
*/
@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
public class MyConfig {
}
@Import 高级用法: https://www.bilibili.com/video/BV1gW411W7wy?p=8
5、@Conditional
条件装配:满足Conditional指定的条件,则进行组件注入
=====================测试条件装配==========================
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
//@ConditionalOnBean(name = "tom")//表示当容器中有tom组件的时候,才会执行下面所有的方法
@ConditionalOnMissingBean(name = "tom")//表示当容器中没有tom组件的时候,执行下面的方法
public class MyConfig {
/**
* Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
* @return
*/
//@ConditionalOnBean(name = "tom")//表示当容器中有tom组件的时候,才会将组件user01注入容器中
@Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
public User user01(){
User zhangsan = new User("zhangsan", 18);
//user组件依赖了Pet组件
zhangsan.setPet(tomcatPet());
return zhangsan;
}
@Bean("tom22")
public Pet tomcatPet(){
return new Pet("tomcat");
}
}
/*############################################*/
public static void main(String[] args) {
//1、返回我们IOC容器
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
//2、查看容器里面的组件
String[] names = run.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}
boolean tom = run.containsBean("tom");
System.out.println("容器中Tom组件:"+tom);
boolean user01 = run.containsBean("user01");
System.out.println("容器中user01组件:"+user01);
boolean tom22 = run.containsBean("tom22");
System.out.println("容器中tom22组件:"+tom22);
}
2.原生配置文件的引入:
1、@ImportResource
======================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.lsy.boot.bean.User">
<property name="name" value="zhangsan"></property>
<property name="age" value="18"></property>
</bean>
<bean id="hehe" class="com.lsy.boot.bean.Pet">
<property name="name" value="tom"></property>
</bean>
</beans>
可以在Config类中再使用@ImportResource注解就可以
:classpath:表示类资源路径:就是resource下面的文件,就可以将Spring配置文件下的组件进行注入
@ImportResource("classpath:beans.xml")
public class MyConfig {}
======================测试=================
boolean haha = run.containsBean("haha");
boolean hehe = run.containsBean("hehe");
System.out.println("haha:"+haha);//true
System.out.println("hehe:"+hehe);//true
3.配置的绑定
如何使用Java读取到properties文件中的内容,并且把它封装到JavaBean中,以供随时使用;
原始的properties文件的读取,需要先读取配置文件,把其中的每一个键值对,将其封装在Javabean中。
public class getProperties {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties pps = new Properties();
pps.load(new FileInputStream("a.properties"));
Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
while(enum1.hasMoreElements()) {
String strKey = (String) enum1.nextElement();
String strValue = pps.getProperty(strKey);
System.out.println(strKey + "=" + strValue);
//封装到JavaBean。
}
}
}
1、@ConfigurationProperties
不能只是单独使用@ConfigurationProperties
方式一:在Bean对象的类添加注解
1、@Component + @ConfigurationProperties
application.xml文件:
package com.lsy.boot.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 只有在容器中的组件,才会拥有SpringBoot提供的强大功能
*/
//先要将组件加入容器中
// 只有在容器中的组件才能拥有Springboot提供的强大功能,例如配置绑定
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
private String brand;
private Integer price;
public Car() {
}
public Car(String brand, Integer price) {
this.brand = brand;
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
@Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
", price=" + price +
'}';
}
}
方式二:在配置类中添加,因为配置类已经在容器中,所以可以不用@Component
2、@EnableConfigurationProperties + @ConfigurationProperties
@EnableConfigurationProperties(绑定的类)的两个功能:
1.表示要开启对谁的配置绑定功能
2.把指定的这个组件自动导入容器中
依旧可以访问成功。
4.自动配置原理
实践场景:
5.开发小技巧:
1、Lombok
简化JavaBean的开发:
引入依赖:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
在idea中搜索安装插件:lombok
在进行Java类的编写的时候,就可以不用写set/get,toString,有参和无参构造器:
如果有其中的一个参数的话,就可以在类中进行构造器的声明
可以加入日志:
@Slf4j
@RestController
public class HelloController {
//自动注入
@Autowired
Car car=new Car();
@GetMapping("/hello")
public String handle01(){
log.info("请求进来了:");
return "Hello,SpringBoot 2!";
}
@GetMapping("/car")
public Car car(){
return car;
}
}
6.dev-tools可以进行热部署:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
改变代码之后,直接按Ctrl+f9就可以进行重新加载。
7.Spring Initailizr的使用