Java 带构造函数参数的Spring组件
我正在使用jdk8,需要创建一个spring组件,该组件将类名作为构造函数参数。但是,使用我当前的代码,我得到了运行时错误:Java 带构造函数参数的Spring组件,java,spring,spring-boot,Java,Spring,Spring Boot,我正在使用jdk8,需要创建一个spring组件,该组件将类名作为构造函数参数。但是,使用我当前的代码,我得到了运行时错误: 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 fina
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 ====================");
}
我可以了解一下创建此组件的正确方法/这里出了什么问题吗?
提前感谢。组件默认为
单例
,因此Spring尝试创建单例实例,但无法确定指定什么作为参数
由于该组件不打算用作单个组件,因此需要将范围更改为prototype
@组件
@范围(“原型”)
公共类多洛格{
有关作用域的更多信息,请参见第节。这篇文章是否回答了您的问题: