如何使用参数创建Spring Bean(DataSource)?

时间:2015-10-26 13:59:55

标签: java spring

同事们,我是Spring 4的新人。 我有一个调用程序的类:

public class ProductDAOImpl implements ProductDAO  {

  public Product getProductUsingProc(int PassID, int Amount) {


        SqlParameterSource sqlParameterSource = new MapSqlParameterSource().addValue("PassID", PassID).addValue("Amount", Amount);
         WebServiceConfig wsc = new WebServiceConfig();

        DataSource dataSource = wsc.DataSource("DB1"); 
        SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("PRODUCT_CREATE");

        Map<String, Object> result = simpleJdbcCall.execute(sqlParameterSource);

        Product product = new Product();

        product.setPassID(PassID); 
        product.setAmount(Amount);
        product.setReturnValue( (int) result.get("ReturnValue") );
        product.setProductID((int) result.get("ProductID"));

        return product;
    }

我需要使用带有不同输入参数的dataSource。

WebServiceConfig(wsc)中的我的bean看起来像:

@Bean
        public BasicDataSource DataSource(String source) {
             /*some code using input parameter*/

            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            dataSource.setUrl("jdbc:....");
            dataSource.setUsername("user");
            dataSource.setPassword("pass");
            dataSource.setMaxIdle(10);
            dataSource.setMaxWaitMillis(10000);
            dataSource.setValidationQuery("select 1");
            dataSource.setTestOnBorrow(false);
            dataSource.setTestWhileIdle(true);
            dataSource.setDefaultAutoCommit(true);
            return dataSource;
        }

但是当运行程序时,我会收到下一个堆栈跟踪:

Error starting ApplicationContext. To display the auto-configuration report enable debug logging (start with --debug)


ERROR: [oct-26 16:46:44,337] springframework.boot.SpringApplication - Application startup failed org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'DataSource' defined in class path resource [com/mayacomp/service/app/WebServiceConfig.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [java.lang. String]: : No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for  this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Depende ncy annotations: {}
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:464)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBean Factory.java:1119)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.jav a:1014)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)

        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
        at com.mayacomp.service.app.WsApplication.main(WsApplication.java:12) Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: e xpected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.jav a:1301)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
        at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813)
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
        ... 18 more Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'DataSource' defined i n class path resource [com/mayacomp/service/app/WebServiceConfig.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [java.lang.String]: : No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifie s as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefiniti onException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate f or this dependency. Dependency annotations: {}
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:464)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBean Factory.java:1119)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.jav a:1014)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)

        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
        at com.mayacomp.service.app.WsApplication.main(WsApplication.java:12) Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: e xpected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.jav a:1301)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
        at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813)
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
        ... 18 more

当我使用bean时没有&#34;字符串来源&#34;它工作正常吗?

更新

我通过为每个数据源使用单独的bean来解决问题:

@Bean
    @Primary
    @ConfigurationProperties(prefix="datasource.primary")
        public BasicDataSource DataSource() {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            dataSource.setUrl("jdbc:sqlserver://");
            dataSource.setUsername("user");
            dataSource.setPassword("pass");
            dataSource.setMaxIdle(10);
            dataSource.setMaxWaitMillis(10000);
            dataSource.setValidationQuery("select 1");
            dataSource.setTestOnBorrow(false);
            dataSource.setTestWhileIdle(true);
            dataSource.setDefaultAutoCommit(true);
            return dataSource;
        }

    @Bean
    @ConfigurationProperties(prefix="datasource.secondary")
    public BasicDataSource DataSource1() {
        BasicDataSource DataSource1 = new BasicDataSource();
        DataSource1.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        DataSource1.setUrl("jdbc:sqlserver://");
        DataSource1.setUsername("user");
        DataSource1.setPassword("pass");
        DataSource1.setMaxIdle(10);
        DataSource1.setMaxWaitMillis(10000);
        DataSource1.setValidationQuery("select 1");
        DataSource1.setTestOnBorrow(false);
        DataSource1.setTestWhileIdle(true);
        DataSource1.setDefaultAutoCommit(true);
        return DataSource1;
    }


    @Bean
    @ConfigurationProperties(prefix="datasource.secondary")
    public BasicDataSource DataSource2() {
        BasicDataSource DataSource2 = new BasicDataSource();
        DataSource2.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        DataSource2.setUrl("jdbc:sqlserver://");
        DataSource2.setUsername("user");
        DataSource2.setPassword("pass");
        DataSource2.setMaxIdle(10);
        DataSource2.setMaxWaitMillis(10000);
        DataSource2.setValidationQuery("select 1");
        DataSource2.setTestOnBorrow(false);
        DataSource2.setTestWhileIdle(true);
        DataSource2.setDefaultAutoCommit(true);
        return DataSource2;
    }

2 个答案:

答案 0 :(得分:3)

当您在使用@Bean注释的方法中传递参数时,每个参数都由spring容器解析,在您的特定情况下,spring无法找到类型为string的bean来满足依赖性,因为您没有设置任何(和你不应该!:))。

如果你想注入一些参数,spring会为你提供@Value注释(这是spring有助于注入属性btw的几种不同方式之一),例如:

_applicationSettings.Value

您需要在资源文件夹中的application.properties文件中定义属性your.property.name,如下所示

your.property.name =我的价值

n.b。

你可以在你的上下文配置文件中使用@PropertySource来从你喜欢的任何地方导入属性http://docs.spring.io/spring-framework/docs/4.0.x/javadoc-api/org/springframework/context/annotation/PropertySource.html(我已经被弹簧启动所破坏了,如果spring自动加载属性,我就忘记了:D)

答案 1 :(得分:0)

您可以在配置中使用@PropertySource(&#34; yourFile.properties&#34;)并通过以下环境获取属性:

    @Configuration
    @PropertySource("yourFile.properties")
    public class YourConfiguration{

        @Autowired
        Environment env

        @Bean
        public BasicDataSource DataSource() {
         String source = env.getProperty("source");
         //your code below
        }
     }

希望这个帮助