【问题标题】:Autowire in An Nonbean Class using AspectJ使用 AspectJ 在非 bean 类中自动装配
【发布时间】:2016-08-31 04:07:30
【问题描述】:

AppConfig 包含 Java 配置。

package com.wh;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableLoadTimeWeaving;
import org.springframework.context.annotation.EnableLoadTimeWeaving.AspectJWeaving;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.aspectj.EnableSpringConfigured;

@Configuration
@EnableSpringConfigured
@EnableLoadTimeWeaving(aspectjWeaving=AspectJWeaving.ENABLED)
public class AppConfig {

    @Bean
    @Lazy
    public EchoService echoService(){

          return new EchoService();
    }
@Bean
    public InstrumentationLoadTimeWeaver loadTimeWeaver()  throws Throwable {
    InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
    return loadTimeWeaver;
    }
}

服务类

package com.wh;

import org.springframework.stereotype.Service;

@Service
public class EchoService {
    public void echo( String s ) {
        System.out.println( s );
    }
}

EchoDelegateService 是非 Bean 类,我们在其中自动装配了所需的 Bean。 我们希望 EchoService 应该自动连接。

问题:EchoService 没有自动连接。给出一个空指针异常。

package com.wh;

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;

@Configurable( preConstruction = true, autowire = Autowire.BY_TYPE, dependencyCheck = false )
public class EchoDelegateService {
    @Autowired
    private EchoService echoService;

    public void echo( String s ) {
        echoService.echo( s );
    }
}

我们调用 NonBean 类方法的主类。

package com.wh;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainApp {
    public static void main(String[] args) {
          ApplicationContext ctx = 
          new AnnotationConfigApplicationContext(AppConfig.class);

          new EchoDelegateService().echo("hihi, it works...");
       }
}

【问题讨论】:

标签: java spring


【解决方案1】:

您的问题已经包含答案:“...在非 bean 类中”。这根本行不通。所有的自动装配、方面解析以及任何相关的内容,适用于 bean。因此,您肯定需要通过 spring 工厂构建 EchoDelegateService:

EchoDelegateService myService = ctx.getBean(EchoDelegateService.class);
myService.echo("this should really work now");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-20
    • 2021-10-09
    相关资源
    最近更新 更多