java—获取在spring中请求bean的类的信息

c3frrgcw  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(378)

考虑到以下类别:

class A
{
    @Inject
    private B b;
}

class B
{

}

@Configuration
class SomeConfiguration
{
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public B b()
    {
        // Is there a way to get the information of the class that requests for this bean within this body of the bean definition method?
        // Ie. the class name of the requesting class 
    }
}

可以在bean定义方法的主体中访问请求类的信息吗?

ubbxdtey

ubbxdtey1#

如果 B 是个记录者,需要知道 A ,则应该使用工厂模式,类似于所有日志框架的工作方式。
日志框架通常只有一个全局工厂。有了Spring,你应该在工厂里注射。
例子:

interface Logger {
    void log(String message);
}

interface LoggerFactory {
    Logger getLogger(Object context);
}

@Component
class MyLoggerFactory implements LoggerFactory {
    @Override
    public Logger getLogger(Object context) {
        return new Logger() {
            @Override
            public void log(String message) {
                System.out.println(context.getClass().getSimpleName() +
                                   " says '" + message + "'");
            }
        }
    }
}

@Component
class A {
    private Logger logger;

    @Inject
    public void setLogger(LoggerFactory factory) {
        this.logger = factory.getLogger(this);
    }
}

相关问题