如何在 SpringBoot 应用程序中自动装配具有带参数的构造函数的组件 [英] How to Autowire a Component which is having constructor with arguments in SpringBoot Application

查看:143
本文介绍了如何在 SpringBoot 应用程序中自动装配具有带参数的构造函数的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有自动装配构造函数的类.

I have a class having Autowired Constructor.

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

now when i am autowiring this class object in my class. how do i pass arguments for constructor??

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

@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 表示不满足的依赖"

"Unsatisfied dependency expressed through constructor parameter 0"

在创建类型为 Transformer 的 bean 时.

while creating bean of type Transformer.

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

how do i pass the arguments to Transformer while Autorwiring it??

推荐答案

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();
    }
}

这篇关于如何在 SpringBoot 应用程序中自动装配具有带参数的构造函数的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆