4.4基于注解+配置类方式整合三层架构组件

2023-12-01  本文已影响0人  大也

package com.atguigu.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;

/**

*/
//@ComponentScan(value = {"com.atguigu.controller","com.atguigu.dao"
// ,"com.atguigu.pojo","com.atguigu.service"})
@ComponentScan("com.atguigu")
@PropertySource("classpath:jdbc.properties")
@Configuration
@Import({ConfigA.class,ConfigB.class})
public class JavaConfig {
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
// @Bean(name = "oneTest",initMethod = "",destroyMethod = "")
@Bean(name = "oneTest")
public DruidDataSource dataSource(
@Value("{atguigu.password}") String password, @Value("{atguigu.username}")
String username,
@Value("{atguigu.url}") String url, @Value("{atguigu.driver}")
String driverClassName
){
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setPassword(password);
druidDataSource.setUsername(username);
druidDataSource.setUrl(url);
druidDataSource.setDriverClassName(driverClassName);
return druidDataSource;
}

@Bean(name = "twoTest")
public DruidDataSource dataSource1(
        @Value("${atguigu.password}")
        String password,
        @Value("${atguigu.username}")
        String username,
        @Value("${atguigu.url}")
        String url,
        @Value("${atguigu.driver}")
        String driverClassName
){
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setPassword(password);
    druidDataSource.setUsername(username);
    druidDataSource.setUrl(url);
    druidDataSource.setDriverClassName(driverClassName);
    return druidDataSource;
}
/**
 *     警告: Exception encountered during context initialization -
 *     cancelling refresh attempt:
 *     org.springframework.beans.factory.UnsatisfiedDependencyException:
 *     Error creating bean with name 'jdbcTemplate' defined
 *     in com.atguigu.config.JavaConfig:
 *     Unsatisfied dependency expressed through method 'jdbcTemplate' parameter 0;
 *     nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException:
 *     No qualifying bean of type 'com.alibaba.druid.pool.DruidDataSource' available:
 *     expected single matching bean but found 2: oneTest,twoTest
 * */


@Bean

// public JdbcTemplate jdbcTemplate(DruidDataSource dataSource){
public JdbcTemplate jdbcTemplate(DruidDataSource twoTest){
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(twoTest);
// jdbcTemplate.setDataSource(dataSource());
return jdbcTemplate;
}
}

上一篇 下一篇

猜你喜欢

热点阅读