【问题标题】:How to Autowire a Component which is having constructor with arguments in SpringBoot Application如何自动装配在 SpringBoot 应用程序中具有带参数的构造函数的组件
【发布时间】:2018-11-09 02:27:47
【问题描述】:

我有一个具有 Autowired 构造函数的类。

现在当我在我的类中自动装配这个类对象时。如何为构造函数传递参数??

示例代码: 具有自动装配构造函数的类:

@Component
public class Transformer {
    private String dataSource;
    @Autowired
    public Transformer(String dataSource)
    {
        this.dataSource = dataSource;
    }
}

对具有带参数的构造函数的组件使用自动装配的类:

@Component
    public class TransformerUser {
        private String dataSource;
        @Autowired
        public TransformerUser(String dataSource)
        {
            this.dataSource = dataSource;
        }
        @Autowired
        Transformer transformer;

    }

此代码失败并显示消息

“通过构造函数参数0表示的不满足的依赖关系”

在创建 Transformer 类型的 bean 时。

如何在 Autorwiring 时将参数传递给 Transformer??

【问题讨论】:

  • 如果你没有 TransformUser,只有 Transformer 类。有用吗?

标签: java spring-boot constructor arguments autowired


【解决方案1】:
package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Transformer {
    private String datasource;

    @Autowired
    public Transformer(String datasource) {
        this.datasource=datasource;
        log.info(datasource);
    }
}

然后创建一个配置文件

package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BeanConfig {
    @Bean
    public Transformer getTransformerBean() {
        return new Transformer("hello spring");
    }

    @Bean
    public String getStringBean() {
        return new String();
    }
}

【讨论】:

  • 这个配置文件应该放在spring boot 项目目录结构的什么位置?
  • 此配置文件与主spring boot应用程序文件一起放置或与主文件并行的包中。
  • 它看起来不像回答这个问题。答案中的 TransformerUser 在哪里...
【解决方案2】:

你可以使用资源文件

1) 定义一个类似于 database.properties 的文件并放置一个类似于

的变量

数据源=示例

在这个文件中

2) 定义一个配置类

@Configuration
@PropertySource(value = {"classpath:resources/database.properties"})
public class PKEServiceFactoryMethod {

   private final Environment environment;

   @Bean
   public String dataSource() {
      return environment.getProperty("dataSource");
   }
}

在这种情况下,您也可以使用比使用构造函数更好的占位符

@Component
@PropertySource(value = {"classpath:resources/database.properties"})
public class Transformer {
    @Value("${dataSource}")
    private String dataSource;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 2022-10-24
    相关资源
    最近更新 更多