首页 > 解决方案 > 带有构造函数参数的 Spring 组件

问题描述

我正在使用 jdk8 并且需要创建一个将类名作为构造函数参数的弹簧组件。但是,使用我当前的代码,我收到运行时错误:

Parameter 0 of constructor in com.some.MyLogger required a bean of type 'java.lang.String' that could not be found

这是我的MyLogger类:

@Component
public class MyLogger {

    protected  final Log logger;

    public MyLogger(String  clazz) {
        logger = LogFactory.getLog(clazz);
    }

    public void debug(String format, Object... args)
    {
        if (logger.isDebugEnabled())
        {
            logger.debug(String.format(format, args));
        }
    }

    public void info(String msg)
    {
        logger.debug(msg);
    }
}

这就是我尝试创建课程的方式:

@SpringBootApplication
public class Application {

    public static void main(String[] args) throws MalformedURLException {
        ApplicationContext context = SpringApplication.run(Application.class, args);
        MyLogger logger = (MyLogger) context.getBean(MyLogger.class, Application.class.getCanonicalName());
        logger.info("================ I AM HERE ====================");
}

我可以了解创建此组件的正确方法/这里出了什么问题吗?提前致谢。

标签: javaspringspring-boot

解决方案


组件是默认的singleton,所以 Spring 尝试创建单例实例,但它不知道要指定什么作为参数。

由于该组件不打算用作单例,因此您需要将范围更改为prototype.

@Component
@Scope("prototype")
public class DuoLogger {

请参阅Spring Framework 文档,第1.5 节。Bean Scopes,有关范围的更多信息。


推荐阅读