[黑马程序员SpringBoot2]——原理篇1

目录:

  1. bean的加载方式(—)
  2. bean的加载方式(二)
  3. bean的加载方式(三)
  4. FactoryBean
  5. proxyBeanMethod属性
  6. bean的加载方式(四)
  7. bean的加载方式(五)
  8. bean的加载方式(六)
  9. bean的加载方式(七)
  10. bean的加载方式(八)
  11. bean加载控制(编程式)
  12. bean加载控制(注解式)
  13. bean依赖属性配置

1.bean的加载方式(—)

XML方式声明bean

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.itheima</groupId><artifactId>springboot_27_bean_init</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.9</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.16</version></dependency></dependencies>
</project>

 

App1.class

package cn.hdc.app;import cn.hdc.bean.Dog;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class App1 {public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext1.xml");
//        Object cat = ctx.getBean("cat");
//        System.out.println(cat);
//
//        Dog dog = ctx.getBean(Dog.class);
//        System.out.println(dog);String[] names = ctx.getBeanDefinitionNames();for (String name : names) {System.out.println(name);}}
}

Cat.class

package cn.hdc.bean;public class Cat {
}

 Dog.class

package cn.hdc.bean;public class Dog {
}

Mouse.class

package cn.hdc.bean;public class Mouse {
}

BookServiceImpl1.class

package cn.hdc.service.impl;import cn.hdc.service.BookService;public class BookServiceImpl1 implements BookService {@Overridepublic void check() {System.out.println("book service 1...");}
}

BookServiceImpl2.class

package cn.hdc.service.impl;import cn.hdc.service.BookService;public class BookServiceImpl2 implements BookService {@Overridepublic void check() {System.out.println("book service 2...");}
}

BookServiceImpl3.class

package cn.hdc.service.impl;import cn.hdc.service.BookService;public class BookServiceImpl3 implements BookService {@Overridepublic void check() {System.out.println("book service 3...");}
}

BookServiceImpl4.class

package cn.hdc.service.impl;import cn.hdc.service.BookService;public class BookServiceImpl3 implements BookService {@Overridepublic void check() {System.out.println("book service 3...");}
}

BookService.interface

package cn.hdc.service;public interface BookService {void check();
}

 applicationContext1.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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="cat" class="cn.hdc.bean.Cat"></bean><bean class="cn.hdc.bean.Dog"></bean><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"></bean>
</beans>

applicationContext2.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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>

 2.bean的加载方式(二)

XML+注解方式声明bean

使用@Component及其衍生注解@Controller . @Service、@Repository定义bean

使用@Bean定义第三方bean,并将所在类定义为配置类或Bean

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><context:component-scan base-package="cn.hdc.bean,cn.hdc.config"/>
</beans>

 App2.class

package cn.hdc.app;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class App2 {public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext2.xml");String[] names = ctx.getBeanDefinitionNames();for (String name : names) {System.out.println(name);}}
}

Dbconfig.class

package cn.hdc.config;import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;@Component
public class DbConfig {@Beanpublic DruidDataSource dataSource() {DruidDataSource ds = new DruidDataSource();return ds;}
}

 

3.bean的加载方式(三)

注解方式声明配置类

 

App3.class

package cn.hdc.app;import cn.hdc.config.SpringConfig3;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App3 {public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig3.class);String[] names = ctx.getBeanDefinitionNames();for (String name : names) {System.out.println(name);}}
}

SpringConfig3.class

package cn.hdc.config;import org.springframework.context.annotation.ComponentScan;@ComponentScan({"cn.hdc.bean","cn,hdc.config"})
public class SpringConfig3 {
}

4.FactoryBean

注解方式声明配置类

@Configuration配置项如果不用于被扫描可以省略

初始化实现FactoryBean接口的类,实现对bean加载到容器之前的批处理操作 

 

App4.class

package cn.hdc.app;import cn.hdc.config.SpringConfig4;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App4 {public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig4.class);String[] names = ctx.getBeanDefinitionNames();for (String name : names) {System.out.println(name);}System.out.println(ctx.getBean("dog"));System.out.println(ctx.getBean("dog"));System.out.println(ctx.getBean("dog"));}
}

 DogFactoryBean.class

package cn.hdc.bean;import org.springframework.beans.factory.FactoryBean;public class DogFactoryBean implements FactoryBean<Dog> {@Overridepublic Dog getObject() throws Exception {return new Dog();}@Overridepublic Class<?> getObjectType() {return Dog.class;}@Overridepublic boolean isSingleton() {return FactoryBean.super.isSingleton();}
}

 SpringConfig4.class

package cn.hdc.config;import cn.hdc.bean.Dog;
import cn.hdc.bean.DogFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;@ComponentScan({"cn.hdc.bean", "cn,hdc.config"})
public class SpringConfig4 {
//    @Bean
//    public Dog dog() {
//        return new Dog();
//    }@Beanpublic DogFactoryBean dog() {return new DogFactoryBean();}
}

5.proxyBeanMethod属性

 加载配置类并加载配置文件(系统迁移)

App32.class

package cn.hdc.app;import cn.hdc.config.SpringConfig32;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App32 {public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig32.class);String[] names = ctx.getBeanDefinitionNames();for (String name : names) {System.out.println(name);}}
}

 SpringConfig32.class

package cn.hdc.config;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
import org.springframework.stereotype.Component;@ComponentScan({"cn.hdc.bean", "cn,hdc.config"})
@ImportResource("applicationContext1.xml")
@Component
public class SpringConfig32 {
}

applicationContext1.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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="cat" class="cn.hdc.bean.Cat"></bean><bean class="cn.hdc.bean.Dog"></bean><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"></bean><bean class="com.alibaba.druid.pool.DruidDataSource"></bean><bean class="com.alibaba.druid.pool.DruidDataSource"></bean>
</beans>

使用proxyBeanMethods=true可以保障调用此方法得到的对象是从容器中获取的而不是重新创建的

 

App33.class

package cn.hdc.app;import cn.hdc.config.SpringConfig33;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App33 {public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig33.class);String[] names = ctx.getBeanDefinitionNames();for (String name : names) {System.out.println(name);}System.out.println("----------------------------");SpringConfig33 springConfig33 = ctx.getBean("springConfig33", SpringConfig33.class);System.out.println(springConfig33.cat());System.out.println(springConfig33.cat());System.out.println(springConfig33.cat());}
}

 SpringConfig33.class

package cn.hdc.config;import cn.hdc.bean.Cat;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration(proxyBeanMethods = false)
public class SpringConfig33 {@Beanpublic Cat cat() {return new Cat();}
}

6.bean的加载方式(四)

使用@Import注解导入要注入的bean对应的字节码

被导入的bean无需使用注解声明为bean 

此形式可以有效的降低源代码与Spring技术的耦合度,在spring技术底层及诸多框架的整合中大量使用

使用@lmport注解导入配置类

 

App4.class

package cn.hdc.app;import cn.hdc.bean.Dog;
import cn.hdc.config.SpringConfig4;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App4 {public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig4.class);String[] names = ctx.getBeanDefinitionNames();for (String name : names) {System.out.println(name);}System.out.println("-----------------");System.out.println(ctx.getBean(Dog.class));}
}

SpringConfig4.class

package cn.hdc.config;import cn.hdc.bean.Dog;
import org.springframework.context.annotation.Import;@Import({Dog.class, DbConfig.class})
public class SpringConfig4 {}

7.bean的加载方式(五)

使用上下文对象在容器初始化完毕后注入bean

 App5.class

package cn.hdc.app;import cn.hdc.bean.Cat;
import cn.hdc.bean.Mouse;
import cn.hdc.config.SpringConfig5;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App5 {public static void main(String[] args) {AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig5.class);ctx.registerBean("tom", Cat.class, 0);ctx.registerBean("tom", Cat.class, 1);ctx.registerBean("tom", Cat.class, 2);ctx.register(Mouse.class);String[] names = ctx.getBeanDefinitionNames();for (String name : names) {System.out.println(name);}System.out.println(ctx.getBean(Cat.class));}
}

SpringConfig5.class

package cn.hdc.config;public class SpringConfig5 {}

Cat.class

package cn.hdc.bean;import org.springframework.stereotype.Component;@Component("tom")
public class Cat {int age;public Cat() {}public Cat(int age) {this.age = age;}@Overridepublic String toString() {return "Cat{" +"age=" + age +'}';}
}

Dog.class

package cn.hdc.bean;import org.springframework.stereotype.Service;//@Service("jerry")
public class Mouse {
}

8.bean的加载方式(六)

导入实现了ImportSelector接口的类,实现对导入源的编程式处理

 App6.class

package cn.hdc.app;import cn.hdc.config.SpringConfig6;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App6 {public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig6.class);String[] names = ctx.getBeanDefinitionNames();for (String name : names) {System.out.println(name);}}
}

SpringConfig.class

package cn.hdc.config;import cn.hdc.bean.MyImportSelector;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;@Import(MyImportSelector.class)
@Configuration
//@ComponentScan(basePackages = "cn.hdc")
public class SpringConfig6 {}

MyImportSelector.class

package cn.hdc.bean;import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;import java.util.Map;public class MyImportSelector implements ImportSelector {@Overridepublic String[] selectImports(AnnotationMetadata metadata) {
//        System.out.println("=======================");
//        System.out.println("提示:" + metadata.getClassName());
//        System.out.println(metadata.hasAnnotation("org.springframework.context.annotation.Configuration"));
//        Map<String, Object> attributes = metadata.getAnnotationAttributes("org.springframework.context.annotation.ComponentScan");
//        System.out.println(attributes);
//        System.out.println("=======================");boolean flag = metadata.hasAnnotation("org.springframework.context.annotation.Configuration");if (flag) {return new String[]{"cn.hdc.bean.Dog"};}return new String[]{"cn.hdc.bean.Cat"};}
}

9.bean的加载方式(七)

导入实现了ImportBeanDefinitionRegistrar接口的类,通过BeanDefinition的注册器注册实名bean,实现对容器中bean的裁定,例如对现有bean的覆盖,进而达成不修改源代码的情况下更换实现的效果

 App7.class

package cn.hdc.app;import cn.hdc.config.SpringConfig7;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App7 {public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig7.class);String[] names = ctx.getBeanDefinitionNames();for (String name : names) {System.out.println(name);}}
}

SpringConfig7.class

package cn.hdc.config;import cn.hdc.bean.MyRegistar;
import org.springframework.context.annotation.Import;@Import(MyRegistar.class)
public class SpringConfig7 {}

MyRegistar.class

package cn.hdc.bean;import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;public class MyRegistar implements ImportBeanDefinitionRegistrar {@Overridepublic void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Dog.class).getBeanDefinition();registry.registerBeanDefinition("red", beanDefinition);}
}

10.bean的加载方式(八)

导入实现了BeanDefinitionRegistryPostProcessor接口的类,通过BeanDefinition的注册器注册实名bean,实现对容器中bean的最终裁定

App8.class

package cn.hdc.app;import cn.hdc.bean.service.BookService;
import cn.hdc.config.SpringConfig8;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App8 {public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig8.class);BookService bookService = ctx.getBean("bookService", BookService.class);bookService.check();}
}

SpringConfig8.class

package cn.hdc.config;import cn.hdc.bean.MyPostProcessor;
import cn.hdc.bean.MyRegistar;
import cn.hdc.bean.MyRegistar2;
import cn.hdc.bean.service.impl.BookServiceImpl1;
import org.springframework.context.annotation.Import;@Import({BookServiceImpl1.class, MyRegistar.class, MyRegistar2.class, MyPostProcessor.class})
public class SpringConfig8 {}

MyRegistar.class

package cn.hdc.bean;import cn.hdc.bean.service.BookService;
import cn.hdc.bean.service.impl.BookServiceImpl2;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;public class MyRegistar implements ImportBeanDefinitionRegistrar {//    @Override
//    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
//        BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Dog.class).getBeanDefinition();
//
//        registry.registerBeanDefinition("red", beanDefinition);
//    }@Overridepublic void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(BookServiceImpl2.class).getBeanDefinition();registry.registerBeanDefinition("bookService", beanDefinition);}
}

MyRegistar2.class

package cn.hdc.bean;import cn.hdc.bean.service.impl.BookServiceImpl2;
import cn.hdc.bean.service.impl.BookServiceImpl3;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;public class MyRegistar2 implements ImportBeanDefinitionRegistrar {//    @Override
//    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
//        BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Dog.class).getBeanDefinition();
//
//        registry.registerBeanDefinition("red", beanDefinition);
//    }@Overridepublic void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(BookServiceImpl3.class).getBeanDefinition();registry.registerBeanDefinition("bookService", beanDefinition);}
}

MyPostProcessor.class

package cn.hdc.bean;import cn.hdc.bean.service.impl.BookServiceImpl4;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;public class MyPostProcessor implements BeanDefinitionRegistryPostProcessor {@Overridepublic void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(BookServiceImpl4.class).getBeanDefinition();registry.registerBeanDefinition("bookService", beanDefinition);}@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {}
}

BookServiceImpl1.class

package cn.hdc.bean.service.impl;import cn.hdc.bean.service.BookService;
import org.springframework.stereotype.Service;@Service("bookService")
public class BookServiceImpl1 implements BookService {@Overridepublic void check() {System.out.println("book service 1...");}
}

BookServiceImpl2.class 

package cn.hdc.bean.service.impl;import cn.hdc.bean.service.BookService;public class BookServiceImpl2 implements BookService {@Overridepublic void check() {System.out.println("book service 2...");}
}

BookServiceImpl3.class  

package cn.hdc.bean.service.impl;import cn.hdc.bean.service.BookService;public class BookServiceImpl3 implements BookService {@Overridepublic void check() {System.out.println("book service 3...");}
}

BookServiceImpl4.class  

package cn.hdc.bean.service.impl;import cn.hdc.bean.service.BookService;public class BookServiceImpl4 implements BookService {@Overridepublic void check() {System.out.println("book service 4...");}
}

11.bean加载控制(编程式)

根据任意条件确认是否加载bean

Cat.class

package cn.hdc.bean;import org.springframework.stereotype.Component;@Component("tom")
public class Cat {
}

Dog.class

package cn.hdc.bean;public class Dog {
}

Mouse.class

package cn.hdc.bean;public class Mouse {
}

MyImportSelector.class

package cn.hdc.bean;import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;public class MyImportSelector implements ImportSelector {@Overridepublic String[] selectImports(AnnotationMetadata annotationMetadata) {try {Class<?> clazz = Class.forName("cn.hdc.bean.Mouse");if (clazz != null) {return new String[]{"cn.hdc.bean.Cat"};}} catch (ClassNotFoundException e) {return new String[0];}return null;}
}

SpringConfig.class

package cn.hdc.config;import cn.hdc.bean.MyImportSelector;
import org.springframework.context.annotation.Import;@Import(MyImportSelector.class)
public class SpringConfig {
}

App.class

package cn.hdc;import cn.hdc.config.SpringConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App {public static void main(String[] args) {ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);String[] beans = context.getBeanDefinitionNames();for (String bean : beans) {System.out.println(bean);}}
}

12.bean加载控制(注解式)

 

根据任意条件确认是否加载bean

 

使用@Conditional注解的派生注解设置各种组合条件控制bean的加载

匹配指定类

未匹配指定类

匹配指定类型的bean

 

匹配指定名称的bean

 

匹配指定环境

 

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>springboot_28_bean_load</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><version>2.5.4</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.16</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.26</version></dependency></dependencies></project>

 Cat.class

package cn.hdc.bean;import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.stereotype.Component;@Component("tom")
@ConditionalOnBean(name = "jerry")
//@ConditionalOnWebApplication
@ConditionalOnNotWebApplication
public class Cat {
}

Dog.class

package cn.hdc.bean;public class Dog {
}

Mouse.class

package cn.hdc.bean;import org.springframework.stereotype.Component;@Component("jerry")
public class Mouse {
}

MyImportSelector.class

package cn.hdc.bean;import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;public class MyImportSelector implements ImportSelector {@Overridepublic String[] selectImports(AnnotationMetadata annotationMetadata) {try {Class<?> clazz = Class.forName("cn.hdc.bean.Mouse");if (clazz != null) {return new String[]{"cn.hdc.bean.Cat"};}} catch (ClassNotFoundException e) {return new String[0];}return null;}
}

SpringConfig.class

package cn.hdc.config;import cn.hdc.bean.Cat;
import cn.hdc.bean.Dog;
import cn.hdc.bean.Mouse;
import cn.hdc.bean.MyImportSelector;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.autoconfigure.condition.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Import;//@Import(MyImportSelector.class)
//@Import(Mouse.class)
@ComponentScan("cn.hdc.bean")
public class SpringConfig {
//    @Bean@ConditionalOnClass(name = "cn.hdc.bean.Mouse")@ConditionalOnMissingClass("cn.hdc.bean.Wolf")
//    @ConditionalOnBean(name = "jerry")@ConditionalOnMissingClass("cn.hdc.bean.Dog")
//    @ConditionalOnNotWebApplication@ConditionalOnWebApplication
//    public Cat tom() {
//        return new Cat();
//    }@Bean@ConditionalOnClass(name = "com.mysql.jdbc.Driver")public DruidDataSource dataSource() {return new DruidDataSource();}
}

13.bean依赖属性配置

将业务功能bean运行需要的资源抽取成独立的属性类(******Properties),设置读取配置文件信息

 

配置文件中使用固定格式为属性类注入数据

定义业务功能bean,通常使用@Import导入,解耦强制加载bean

使用@EnableConfigurationProperties注解设定使用属性类时加载bean

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.5.6</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>springboot_29_bean_properties</artifactId><version>0.0.1-SNAPSHOT</version><name>springboot_29_bean_properties</name><description>springboot_29_bean_properties</description><properties><java.version>8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><image><builder>paketobuildpacks/builder-jammy-base:latest</builder></image></configuration></plugin></plugins></build></project>

CartoonCatAndMouse.class

package com.example.springboot_29_bean_properties.bean;import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;@Data
@EnableConfigurationProperties(CartoonProperties.class)
public class CartoonCatAndMouse {private Cat cat;private Mouse mouse;private CartoonProperties cartoonProperties;public CartoonCatAndMouse(CartoonProperties cartoonProperties) {this.cartoonProperties = cartoonProperties;cat = new Cat();cat.setName(cartoonProperties.getCat() != null && StringUtils.hasText(cartoonProperties.getCat().getName()) ? cartoonProperties.getCat().getName() : "tom");cat.setAge(cartoonProperties.getCat() != null && cartoonProperties.getCat().getAge() != null ? cartoonProperties.getCat().getAge() : 3);mouse = new Mouse();mouse.setName(cartoonProperties.getMouse() != null && StringUtils.hasText(cartoonProperties.getCat().getName()) ? cartoonProperties.getMouse().getName() : "jerry");mouse.setAge(cartoonProperties.getMouse() != null && cartoonProperties.getMouse().getAge() != null ? cartoonProperties.getMouse().getAge() : 4);}public void play() {System.out.println(cat.getAge() + "岁的" + cat.getName() + "和" + mouse.getAge() + "岁的" + mouse.getName() + "打起来了");}
}

CartoonProperties.class

package com.example.springboot_29_bean_properties.bean;import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;@ConfigurationProperties(prefix = "cartoon")
@Data
public class CartoonProperties {private Cat cat;private Mouse mouse;
}

Cat.class

package com.example.springboot_29_bean_properties.bean;import lombok.Data;@Data
public class Cat {private String name;private Integer age;
}

 Mouse.class

package com.example.springboot_29_bean_properties.bean;import lombok.Data;@Data
public class Mouse {private String name;private Integer age;
}

Springboot29BeanPropertiesApplicaiton.class

package com.example.springboot_29_bean_properties;import com.example.springboot_29_bean_properties.bean.CartoonCatAndMouse;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Import;@SpringBootApplication
@Import(CartoonCatAndMouse.class)
public class Springboot29BeanPropertiesApplication {public static void main(String[] args) {ConfigurableApplicationContext ctx = SpringApplication.run(Springboot29BeanPropertiesApplication.class, args);CartoonCatAndMouse bean = ctx.getBean(CartoonCatAndMouse.class);bean.play();}
}

小结:

  • 业务bean的属性可以为其设定默认值
  • 当需要设置时通过配置文件传递属性
  • 业务bean应尽量避免设置强制加载,而是根据需要导入后加载,降低spring容器管理bean的强度 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/168773.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

[ZJCTF 2019]NiZhuanSiWei

虽然有include函数但我们无法直接包含flag因为对file进行了过滤&#xff0c;又看见有反序列化的入口&#xff0c;只是并没有发现可利用的方法&#xff0c;但题目有提示所以尝试将其调出来 php伪协议写入内容 看到file_get_contents函数想到使用data协议&#xff0c;去封装一个…

Hive内置表生成函数

Hive内置UDTF 1、UDF、UDAF、UDTF简介2、Hive内置UDTF 1、UDF、UDAF、UDTF简介 在Hive中&#xff0c;所有的运算符和用户定义函数&#xff0c;包括用户定义的和内置的&#xff0c;统称为UDF&#xff08;User-Defined Functions&#xff09;。如下图所示&#xff1a; UDF官方文档…

远程安全访问JumpServer:使用cpolar内网穿透搭建固定公网地址

文章目录 前言1. 安装Jump server2. 本地访问jump server3. 安装 cpolar内网穿透软件4. 配置Jump server公网访问地址5. 公网远程访问Jump server6. 固定Jump server公网地址 前言 JumpServer 是广受欢迎的开源堡垒机&#xff0c;是符合 4A 规范的专业运维安全审计系统。JumpS…

Python潮流周刊:Twitter 的强敌 Threads 是用 Python 开发的!

&#x1f984;文章&教程 1、聊一聊 Python 和 Golang 的垃圾回收 常见的垃圾回收算法有哪些&#xff0c;它们的优缺点是什么&#xff1f;Python 的垃圾回收机制由什么组成&#xff0c;如何解决内存泄漏问题&#xff1f;Golang 的垃圾回收机制又是怎样的&#xff0c;如何解…

新式的拉式膜片弹簧离合器设计机械设计CAD

wx供重浩&#xff1a;创享日记 对话框发送&#xff1a;离合器 获取完整论文报告工程源文件 减震弹簧 摩擦片 膜片弹簧 压盘 轴 扭转减震器 从动盘 离合器 离合器的结构设计 为了达到计划书所给的数据要求&#xff0c;设计时应根据车型的类别、使用要求、制造条件&#xff0c;…

C#,《小白学程序》第四课:数学计算,总和与平均值

程序是 数据 计算 显示。 1 文本格式 /// <summary> /// 《小白学程序》第四课&#xff1a;数学计算 /// 这节课超级简单&#xff0c;就是计算成绩的平均值&#xff08;平均分&#xff09; /// 这个是老师们经常做的一件事。 /// </summary> /// <param name&…

洛谷P1049装箱问题 ————递归+剪枝+回溯

没没没没没没没没没错&#xff0c;又是一道简单的递归&#xff0c;只不过加了剪枝&#xff0c;我已经不想再多说&#xff0c;这道题写了一开始写了普通深搜&#xff0c;然后tle了一个点&#xff0c;后面改成剪枝&#xff0c;就ac了&#xff0c;虽然数据很水&#xff0c;但是不妨…

ruoyi-plus-vue docker 部署

本文以 ruoyi-vue-plus 5.x docker 部署为基础 安装虚拟机 部署文档 安装docker 安装docker 安装docker-compose 配置idea环境 上传 /doicker 文件夹 到服务器&#xff1b;赋值 777权限 chmod -R 777 /docker idea构建 jar 包 利用 idea 构建镜像; 创建基础服务 docker…

力扣 3. 无重复字符的最长子串

题目 题解 方法 public static int lengthOfLongestSubstring(String s) {HashSet<Character> charSet new HashSet<Character>();int i 0,l0,max0;for (int j 0; j < s.length(); j) {while (charSet.contains(s.charAt(j))) {charSet.remove(s.charAt(l…

【JavaEE初阶】Thread 类及常见方法、线程的状态

目录 1、Thread 类及常见方法 1.1 Thread 的常见构造方法 1.2 Thread 的几个常见属性 1.3 启动⼀个线程 - start() 1.4 中断⼀个线程 1.5 等待⼀个线程 - join() 1.6 获取当前线程引用 1.7 休眠当前线程 2、线程的状态 2.1 观察线程的所有状态 2.2 线程状态和状…

硬盘上不小心删除了重要文档?试试这6个成功率高的数据恢复工具!

您是否不小心重新格式化了存储卡或删除了想要保留的照片&#xff1f;最好的照片恢复软件可以提供帮助&#xff01;如果您使用数码相机拍摄的时间足够长&#xff0c;那么当您错误地删除了想要保留的图像、重新格式化了错误的 SD 卡&#xff0c;或者发现您的珍贵照片由于某种莫名…

CFO的GenAI应用指南

CFO应该采取的最重要行动是识别最大的创造价值的机会&#xff0c;然后确保他们获得所需的资金和其他资源。GenAI拥有成为革命性技术的潜力&#xff0c;但它不会改变金融和经济学的基本原则&#xff1a;一家公司必须产生高于资本成本的回报。 技术改变了每一项业务&#xff0c;往…

分布式锁,分布式锁应该具备哪些条件,分布式锁的实现方式有:基于Zookeeper实现、Redis实现、数据库实现

文章目录 分布式锁0-1分布式锁--包含CAP理论模型概述分布式锁&#xff1a;分布式锁应该具备哪些条件&#xff1a;分布式锁的业务场景&#xff1a; 分布式锁的实现方式有&#xff1a;基于Zookeeper - 分布式锁实现思想优缺点基于Redis - 分布式锁实现思想实现思想的具体步骤&…

【LeetCode 热题 HOT 100】题解笔记 —— Day01

❤ 作者主页&#xff1a;欢迎来到我的技术博客&#x1f60e; ❀ 个人介绍&#xff1a;大家好&#xff0c;本人热衷于Java后端开发&#xff0c;欢迎来交流学习哦&#xff01;(&#xffe3;▽&#xffe3;)~* &#x1f34a; 如果文章对您有帮助&#xff0c;记得关注、点赞、收藏、…

企业海外分部,如何实现安全稳定的跨境网络互连?

如今&#xff0c;众多企业广泛采取数字化业务系统&#xff0c;如OA、ERP及CRM等&#xff0c;来提升其业务运营效率。同时&#xff0c;私有云与公有云混合架构也逐渐普及化。 具体来说&#xff0c;很多企业选择将研发系统部署在公司本地的私有云环境&#xff0c;以此确保数据安全…

首批!创邻科技入选《图数据库金融应用场景优秀案例》

11月11日&#xff0c;“全球金融科技中心网络年会”在第三届全球金融科技大会暨第五届成方金融科技论坛上成功在京举办。会上&#xff0c;北京前沿金融监管科技研究院发布了基于国际标准组织——国际关联数据基准委员会&#xff08;LDBC&#xff09;的《图数据库金融应用场景优…

路由器DHCP分配IP地址规则

路由器DHCP分配IP地址的机制&#xff1a; 先设置一个IP地址池&#xff0c;假设是192.168.1.100-192.168.1.199一共100个。 来一个请求&#xff0c;看一下是不是以前请求过的地址&#xff0c;如果是&#xff0c;还是返回以前给过的IP&#xff0c;然后将到期时间(有些路由器默认…

【Python3】【力扣题】349. 两个数组的交集

【力扣题】题目描述&#xff1a; 【Python3】代码&#xff1a; 1、解题思路&#xff1a;集合的交集。两个数组都转为集合&#xff0c;获取集合的交集。 知识点&#xff1a;set(...)&#xff1a;转为集合&#xff0c;集合的元素不重复。 集合1.intersection(集合2)&#xff1a…

Python3.7 win7系统安装openCV方案

为了使用机房电脑处理数字图像问题&#xff0c;在win7系统安装了python opencv, 测试使用的是官网下载python3.7.7版本&#xff0c;如果官网安装&#xff0c;直接安装即可 pip install python-opencv 这样会自动安装对应版本的numpy 如果官网安装很慢&#xff0c;想使用镜像安…

【Linux】EVIOCGBIT

EVIOCGBIT(ev, len) 该怎么理解&#xff1f; 我们可以推断出&#xff0c;它是一个宏&#xff0c;它的前两个参数已经确定了&#xff0c;具体的功能由后两个参数(ev,len)来决定。Linux-4.9.88\include\uapi\linux\input.h #define EVIOCGBIT(ev,len) _IOC(_IOC_READ, E, 0x20 …