java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Springboot控制反转

Springboot控制反转与Bean对象的方法

作者:CodingFang

文章介绍了Spring Boot中的控制反转(IoC)概念,描述了IoC容器如何管理Bean的生命周期和依赖关系,它详细讲解了Bean的注册过程,包括通过@ComponentScan和@Bean注解的方式,并讨论了Bean的依赖注入方法,如构造器注入、Setter注入和字段注入,感兴趣的朋友一起看看吧

1 控制反转

1.1 什么是控制反转

控制反转(IoC)是一种设计原则,它将对象的创建、依赖注入和生命周期管理等责任从应用程序代码中转移到框架或容器中

1.2 SpringBoot中的控制反转

Spring框架通过IoC容器来管理Bean的生命周期和依赖关系,从而实现控制反转

2 Ioc容器对Bean的管理

2.1 什么是Bean对象?

在Spring框架中,Bean是一个由Spring IoC容器管理的对象。Bean的创建、初始化、依赖注入以及销毁都由Spring容器负责。Bean可以是任何Java对象,通常是一个POJO(Plain Old Java Object)。

2.2 Bean的注册过程

2.2.1 扫描Bean

@Configuration   
@ComponentScan(basePackages = {"com.example.service", "com.example.repository"})   
public class AppConfig {
}

2.2.2 定义Bean

使用@Component及其派生注解:Spring支持通过@ComponentScan自动扫描并注册Bean。常用的注解包括:

    @Component:通用注解,用于标记任意类为 Bean。
    @Service:用于标记服务层的类。
    @Repository:用于标记数据访问层的类。
    @Controller:用于标记控制器层的类。
    @Configuration:用于标记配置类。

使用@Bean注解:在配置类中,可以使用@Bean注解显式定义Bean。@Bean通常用于定义第三方库中的类或需要自定义配置的Bean。

@Configuration// 配置注解
public class CommonConfig {
    /**
     * @Bean注解标注的方法会被 Spring容器调用,并将返回值注册为一个 Bean
     */
    @Bean
    public Country country(){
        return new Country();
    }
     /**
     * 默认情况下,Bean 的名称是方法名。你可以通过name或value属性指定Bean的名称。
     */
    @Bean(name = "customService")
    public MyService myService() {
        //Bean 的名称为 customService,而不是默认的 myService。
        return new MyService();
    }
}

3.基于 XML 配置的注册:早期的 Spring 版本中,Bean 通常通过 XML 配置文件注册。虽然现在推荐使用注解,但 XML 配置仍然支持

<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 -->
    <bean id="myService" class="com.example.MyService"/>
</beans>

条件化的 Bean 注册:可以结合条件注解(如 @ConditionalOnProperty、@ConditionalOnClass 等)实现条件化的 Bean 注册

CommonConfig.java

@Configuration
public class CommonConfig {
    /**
     * 使用@ConditionalOnProperty 条件注入:配置文件中前缀是province,属性名为name的值若是wfs,则声明此Bean
     * @ConditionalOnMissingBean 当不存在当前类型的bean时,才声明该bean
     * @ConditionalOnClass 当classpath下存在指定类时,才声明该bean
     */
    @ConditionalOnProperty(prefix = "province",name = "name" ,havingValue = "wfs")
    @ConditionalOnMissingBean
    @ConditionalOnClass(name = "com.wfs.config.CommonConfig")
    public Province province(@Value("${province.name}") String name,
                             @Value("${province.direction}") String direction) {
        Province province = new Province();
        province.setName(name);
        province.setDirection(direction);
        return province;
    }
}

2.3 @import注解

@Import注解用于将其他配置类或组件引入到当前配置类中。它提供了一种模块化的方式来组织Spring应用的配置,避免将所有配置集中在一个类中。优先使用@ComponentScan:如果可以通过@ComponentScan扫描到的类,尽量使用@ComponentScan而不是@Import。如下面的例子:

启动类

/*
1@Import 可以标注在 @Configuration 类或 @Component 类上,用于导入其他配置类或组件类
2@Import 可以同时导入多个配置类。
3@Import 还可以导入实现了 ImportSelector 接口的类,用于动态选择需要导入的配置类或组件类
*/
@Import(com.wfs.config.CommonImportSeletor.class)//使用@Import导入ImportSelector
//@Import(com.wfs.config.CommonConfig.class)
@SpringBootApplication
public class SpringbootBeanRegisterApplication {
    public static void main(String[] args) {
      ApplicationContext context =  SpringApplication.run(SpringbootBeanRegisterApplication.class, args);//获取ioc容器
      Country country = context.getBean(Country.class);//获取bean
      System.out.println(country);
      System.out.println(context.getBean("aa"));

CommonImportSeletor.java

/**
 * @ImportSelector:导入选择器
 * 作用:导入指定配置类
 */
public class CommonImportSeletor implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[]{"com.wfs.config.CommonConfig"};
    }
}

2.4 Bean的注册顺序

2.5 Bean的依赖注入

构造器注入:推荐的方式,适用于强制依赖。

@Service
public class MyService {
    private final MyRepository repository;
    @Autowired
    public MyService(MyRepository repository) {
        this.repository = repository;
    }
}

Setter 注入:适用于可选依赖

@Service
public class MyService {
    private MyRepository repository;
    @Autowired
    public void setRepository(MyRepository repository) {
        this.repository = repository;
    }
}

字段注入:不推荐,因为不利于测试和代码可读性。

@Service
public class MyService {
    @Autowired
    private MyRepository repository;
}

到此这篇关于Springboot控制反转与Bean对象的文章就介绍到这了,更多相关Springboot控制反转内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文