java - 带有构造函数参数的 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 ====================");
}
我可以了解创建此组件的正确方法/这里出了什么问题吗?提前致谢。
解决方案
组件是默认的singleton
,所以 Spring 尝试创建单例实例,但它不知道要指定什么作为参数。
由于该组件不打算用作单例,因此您需要将范围更改为prototype
.
@Component
@Scope("prototype")
public class DuoLogger {
请参阅Spring Framework 文档,第1.5 节。Bean Scopes,有关范围的更多信息。
推荐阅读
- java - 基于参数在父类中使用子类的静态成员
- firebase - Firestore:如何查询集合中的多个动态值
- c# - UWP C# 将音频设备设备信息显示到文本块
- c++ - 我应该使用 lambda 或仿函数进行比较函数吗?
- node.js - Microsoft Bot Framework - 在多个对话框中使用变量 (node.js)
- unity3d - 为什么我不能让子 UI 元素移动到 x 轴上相对于其父位置的位置 0(在这种情况下是画布)?
- c# - MRTK V2 - 旁观者视图:看不到动态纹理
- python - 为刻度标签设置(条件)字体粗细
- reactjs - 查询 useEffect - React Hooks
- git - 如何在git中删除文件的合并历史