首页 > 其他分享 >配置类方式管理Bean

配置类方式管理Bean

时间:2024-07-18 22:09:24浏览次数:5  
标签:方式 配置 bean Bean dataSource public jdbcTemplate JdbcTemplate

配置类方式管理Bean

1.完全注解开发

配置类是用来替代 xml 配置文件

在注解+xml方式开发中,第三方的类还是需要在xml中去配置。而使用配置类可以在方法上用注解来替代xml标签

这种开发方式叫做完全注解开发。

 

2.配置类

2.1无第三方组件

在没有引入第三方类的情况下,xml文件中,有扫描注解的包和引入外部文件的标签。<context:component-scan 和 <context:property-placeholder

在配置类中,是这样实现这两个功能的

  • 首先用 @Configuration 注解标识一个类是配置类

  • @ComponentScan 注解是用来扫描包的

    它的参数是一个数组,如果只有一个包那么可以省略花括号 @ComponentScan("com.ztone.ioc_01")

    如果有多个包,@ComponentScan({"com.ztone.ioc_01","com.ztone.ioc_02"})

    这两种写法都省略了value= ,前提是只有value这一种类型的参数

  • @PropertySource 注解是用来指定外部的文件

    @PropertySource(value="classpath:jdbc.properties")

@Configuration
@ComponentScan("com.ztone.ioc_01")
@PropertySource("classpath:jdbc.properties")
public class JavaConfiguration {
    
}

 

在使用配置类时,就是创建ioc容器的时候,用的实现类是 AnnotationConfigApplicationContext

参数就是这个配置类的类型

@Test
public void test_01(){
    AnnotationConfigApplicationContext applicationContext
            = new AnnotationConfigApplicationContext(JavaConfiguration.class);
    applicationContext.getBean(StudentController.class);
​
//        第二种方式
//        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
//        context.register(JavaConfiguration.class);
//        context.refresh();
​
}

2.2配置第三方组件

上面的那种情况是没有使用到第三方的类,并且可以注意到 配置类中也没有东西。如果用到了第三方的类,可以用 @Bean 注解来引入

在xml文件中配置数据库连接池

image-20240718201334945

现在用一个方法去替代 bean 标签

该方法的返回值 是 bean标签中的class属性对应的类型或其接口和父类

该方法的名字 是 bean标签中的 id

在该方法中通过new的方式 实例化需要的类型并返回

最后在该方法上使用 @Bean 标签,@Bean标签可以用name或value属性来指定bean的名字,不指定默认是方法名

@Configuration
@ComponentScan("com.ztone.ioc_01")
@PropertySource("classpath:jdbc.properties")
public class JavaConfiguration {
​
    @Bean
    public DruidDataSource dataSource(@Value("${url}") String url , 
                                      @Value("${driver}") String driver,
                                      @Value("${username1}")String username,
                                      @Value("${password}")String password){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(url);
        druidDataSource.setUrl(driver);
        druidDataSource.setUrl(username);
        druidDataSource.setUrl(password);
        return druidDataSource;
    }
}

这个方法可以有形参,这四个形参都是从外部文件中读取出来的,如果某个形参在别的方法中也用到了,也可以定义成全局属性。

 

2.3在bean方法中引用其他bean

在bean方法中引用其他bean,比如JdbcTemplate 需要引入 DataSource,有两种方式

  • 第一种直接调用 需要的bean方法

    @Bean
    public DruidDataSource dataSource(@Value("${url}") String url ,
                                      @Value("${driver}") String driver,
                                      @Value("${username1}")String username,
                                      @Value("${password}")String password){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(url);
        druidDataSource.setUrl(driver);
        druidDataSource.setUrl(username);
        druidDataSource.setUrl(password);
        return druidDataSource;
    }
    ​
    @Bean
    public JdbcTemplate jdbcTemplate(){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource("xxx","xxx","xxx","xxx"));
        return jdbcTemplate;
    }

    说不推荐的原因大概是需要自己传入参数,而前面我们的形参已经指定是从文件中读取的了

  • 第二种:需要的类型作为形参传入,交由ioc容器去判断该注入哪个 bean,这种方式必须保证ioc容器中有该类型的组件,如果没有会报错。如果有多个该类型的组件,形参的名字是组件的id,就可以区分注入的是哪个

    @Bean
    public JdbcTemplate jdbcTemplate2(DataSource dataSource){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

 

bean的其他属性,可以指定该bean的初始方法和销毁方法

@Bean(value="myjdbc",initMethod = "init",destroyMethod = "destory")
public JdbcTemplate jdbcTemplate2(DataSource dataSource){
    JdbcTemplate jdbcTemplate = new JdbcTemplate();
    jdbcTemplate.setDataSource(dataSource);
    return jdbcTemplate;
}

当然也可以使用 @PostConstruct 和 @PreDestory 来指定

在该方法上也可以用 @Scope 注解来指定该组件是单例还是多例

 

2.4 Import注解

当我们有多个配置类时,在往ioc容器中放的时候需要把每个配置类都逐个写入。一旦配置类太多,写起来就会很麻烦冗余,这时可以把这些配置类都整合到一个配置类中,在实例化ioc容器时只写一个配置类就行了

那么如何将多个配置类整合到一个配置类中呢,这里就用到了 @Import 注解

@Import(value = JavaConfigrationB.class)
@Configuration
public class JavaConfigrationA {
}

多个配置类用花括号包起来

 

2.5 三层架构案例-配置类实现

  1. 配置类

    package com.ztone.config;
    ​
    import com.alibaba.druid.pool.DruidDataSource;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.jdbc.core.JdbcTemplate;
    ​
    @Configuration
    @ComponentScan("com.ztone")
    @PropertySource("classpath:jdbc.properties")
    public class JavaConfigration {
    ​
        //配置 dataSource Bean
        @Bean
        public DruidDataSource dataSource(
                @Value("${url}") String url,
                @Value("${driver}") String driver,
                @Value("${username1}") String username,
                @Value("${password}") String password){
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(url);
            dataSource.setDriverClassName(driver);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
    ​
            return dataSource;
        }
    ​
        //配置 JdbcTemplate bean
        @Bean
        public JdbcTemplate jdbcTemplate(DruidDataSource dataSource){
            JdbcTemplate jdbcTemplate = new JdbcTemplate();
            jdbcTemplate.setDataSource(dataSource);
            return jdbcTemplate;
        }
    }

三层架构和注释中的案例相同

ioc容器

public class SpringTest {
    @Test
    public void test(){
        AnnotationConfigApplicationContext applicationContext
                = new AnnotationConfigApplicationContext(JavaConfigration.class);
        StudentController bean = applicationContext.getBean(StudentController.class);
​
        bean.searchStudent();
    }
}

标签:方式,配置,bean,Bean,dataSource,public,jdbcTemplate,JdbcTemplate
From: https://www.cnblogs.com/wztblogs/p/18310505

相关文章

  • 内核配置
    https://developer.aliyun.com/article/536805https://help.aliyun.com/zh/ecs/support/common-kernel-network-parameters-of-ecs-linux-instances-and-faq-hosts:allgather_facts:nobecome:yestasks:#-name:Insertcontentbelowaspecificline#......
  • 基于注解方式组件管理
    基于注解方式组件管理之前是通过在xml文件中向ioc容器中配置bean,通过<bean标签的方式,注解的方式是在Java类上使用注解标记某个类,将该类配置到ioc容器。主要分成两步:在类上使用注解让ioc识别那些类加了注解1.注解的ioc配置spring提供了以下几个注解,直接标记在类上,把他......
  • camke(11)配置g2o
     适配openvslam和slam14讲解代码版本1.Eigen安装(最新3.3.7)wget-qhttps://gitlab.com/libeigen/eigen/-/archive/3.3.7/eigen-3.3.7.tar.bz2tarxfeigen-3.3.7.tar.bz2rm-rfeigen-3.3.7.tar.bz2cdeigen-3.3.7mkdir-pbuild&&cdbuildcmake\-DCMAKE_BU......
  • 配置VMware静态IP
    方便远程办公,找IP1.在VMware中找到原有的IP,网关,子网掩码1.2点击虚拟网络编辑器-->点击NAT设置即可看到IP..........记住2.登陆root用户,打开终端编译2.1再ll进行查看2.2再cdnetwork-scripts2.3再viifcfg-ens332.4用到第一步中所查到的数据,IPADDR最后几位随意......
  • 支持语音电话、短信、企业微信、钉钉、APP、第三方接口、音柱等多种告警通知方式的智
    AI视频监控平台简介AI视频监控平台是一款功能强大且简单易用的实时算法视频监控系统。它的愿景是最底层打通各大芯片厂商相互间的壁垒,省去繁琐重复的适配流程,实现芯片、算法、应用的全流程组合,从而大大减少企业级应用约95%的开发成本。用户只需在界面上进行简单的操作,就可以实......
  • K3s 修改 CoreDNS 配置,持久生效
    K3s启动后,会自动帮我们安装好CoreDNS,不需要手动安装。如果你想修改CoreDNS的配置,常用的有两种方式:直接修改CoreDNS的configmap来调整CoreDNS的参数,例如:kubectl-nkube-systemeditconfigmapcoredns修改K3smanifests中的CoreDNS配置文件,文件位置:/var/lib/r......
  • 第三节 JMeter安装及配置
    1.官网地址下载(1)JDK:https://www.oracle.com/cn/java/technologies/downloads/,下载1.8版本以上的,最好下载最新版本(本次下载本次下载了jdk-22)。(2)JMeter:https://jmeter.apache.org/,下载最新版本即可(本次下载了apache-jmeter-5.6.3)。2.环境变量配置(1)JDK安装及配置:  ①安装:可安装......
  • springboot访问多个mysql数据库配置多数据源
    一、参考地址:https://github.com/baomidou/dynamic-datasource二、使用方法引入dynamic-datasource-spring-boot-starter或者dynamic-datasource-spring-boot3-starter。spring-boot1.5.x2.x.x点击查看代码<dependency><groupId>com.baomidou</groupId><art......
  • AI绘画可以通过这四种方式盈利变现
    市场上涌现出许多利用AI绘画吸引用户并实现盈利的方式。相信很多朋友已经有所耳闻,然而如何将其转化为真金白银却令人摸不着头脑。今天,我们将为大家详细揭示这个项目的操作秘籍,它具备低门槛、简单易行、变现潜力无限的特点,就像是为你奉上一个赚钱的锦囊妙计。一、什么是AI......
  • request请求方式(post请求)
    这里我们定义一个html的静态文件,模拟用户正常提交表单  业务代码实现:fromflaskimportFlask,requestapp=Flask(__name__)@app.route('/test2',methods=['POST'])deftest2():name=request.form.get('user_name')age=request.form.get('user_age&......