简体   繁体   English

在 spring 中将 bean 注入手动实例化的 class

[英]Inject a bean into a manually instantiated class in spring

I've got some domain classes that I'm using.我有一些我正在使用的域类。 There is a requirement for logging in them, but it doesn't look like spring will allow you to inject a bean into a manually instantiated object.需要登录它们,但看起来 spring 不允许您将 bean 注入手动实例化的 object。 I don't want to have to pass the logger as a parameter to constructor because this logger is a bean that I'm autowiring into most of my classes.我不想将记录器作为参数传递给构造函数,因为这个记录器是一个 bean,我正在自动装配到我的大多数类中。 It looks a little bit like this:它看起来有点像这样:

public class MainClass {
    private Logger logger;
    public MainClass(Logger logger) {
        this.logger = logger;
    }
    public void doThing() {
        //..do stuff
        DomainClass domainObject = new DomainClass(//params);
    }
}

public class DomainClass {
    //bunch of fields
    
    //field I want to autowire
    private Logger logger;
}

@Component
public class Logger {
    //stuff
}

Is there any way to achieve this without passing the logger as a parameter?有没有办法在不将记录器作为参数传递的情况下实现这一点?

There is a lot of great Java logging libraries that do not require you to drag the logger around.有很多很棒的 Java 日志库,不需要您拖动记录器。 For example, the logging in SLF4J looks like this:例如,SLF4J 中的日志记录如下所示:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MainClass {
    private static final Logger logger = LoggerFactory.getLogger(MainClass.class);

    public MainClass() { }
    
    public void doThing(String userInput) {
        ...
        logger.info("Info message");
        logger.debug("Debug message");
        logger.error("Error message with an argument: {}", userInput);
        ...
    }
}

As you see, SLF4J does not require you to register the logger in the IoC container and instead relies on the static factory method LoggerFactory.getLogger .如您所见,SLF4J 不需要您在 IoC 容器中注册记录器,而是依赖于 static 工厂方法LoggerFactory.getLogger

I just can't emphasize how nice and configurable Java logging libraries are compared to any hand-written logger.我无法强调与任何手写记录器相比,Java 日志库有多好和可配置。 I recommend you to use an existing and well established logging library, for example the combination SLF4J + Logback that Spring Boot uses by default.我建议您使用现有且完善的日志记录库,例如 Spring Boot 默认使用的组合 SLF4J + Logback。

If you can't use a third-party logging library for your use case, consider managing your MainClass and other classes like this in the IoC container together with the logger.如果您的用例不能使用第三方日志库,请考虑在 IoC 容器中与记录器一起管理您的MainClass和其他类似的类。 This way you'll have the full power of Spring auto-wiring at your fingertips.通过这种方式,您将拥有 Spring 自动接线的全部功能,触手可及。 Spring can't do anything about objects you create yourself. Spring 对您自己创建的对象无能为力。 Spring operates only on the objects in its IoC container. Spring 仅对其 IoC 容器中的对象进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM