Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用普通java类和Springbean是行不通的_Spring - Fatal编程技术网

使用普通java类和Springbean是行不通的

使用普通java类和Springbean是行不通的,spring,Spring,我有一个实用程序类,它没有任何注释@component 我在实用程序类中声明了几个自动连接的服务类变量,但是在方法内部访问时,它们都是null 如何在实用程序类中使用Springbean? 我们是否需要强制将实用程序类标记为@component? 我已经在基本扫描包中包含了实用程序类,但它不起作用 无法获取应用程序上下文以加载服务类,因为它返回null?我们需要通过应用程序上下文加载服务类吗 谢谢。您不理解Spring的bean的概念,所有标有@Component的类都由Spring CDI管理

我有一个实用程序类,它没有任何注释@component

我在实用程序类中声明了几个自动连接的服务类变量,但是在方法内部访问时,它们都是null

如何在实用程序类中使用Springbean? 我们是否需要强制将实用程序类标记为@component? 我已经在基本扫描包中包含了实用程序类,但它不起作用 无法获取应用程序上下文以加载服务类,因为它返回null?我们需要通过应用程序上下文加载服务类吗
谢谢。

您不理解Spring的bean的概念,所有标有@Component的类都由Spring CDI管理

@ComponentScan只向CDI添加标有@Component的类或带有@Component注释的其他类,例如@Service

不能在简单的java类中使用Springbean

但是,如果您真的需要,您可以使用以下代码,我不推荐使用它,因为在这里您将使用Spring作为变通解决方案

@Component
public final class BeanInjector implements ApplicationContextAware{


    private BeanInjector(){}
    private static ApplicationContext context;

    @Override
    public synchronized void setApplicationContext(final ApplicationContext ac) throws BeansException {
        context = ac;
    }

    public static <T> T getBean(final Class<T> beanClass) {
        return context.getBean(beanClass);
    }

}
public class Pojo(
  void smth(){
   BeanInjector.getBean(ClassAnnotatedWithComponent.class);

}

)