有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring:@Autowired,不带@Component

在一个实际的项目中,我发现@Component可能在以下代码中被省略:

// no @Component !!!!!
public class MovieRecommender {

    private final CustomerPreference customerPreference;

    @Autowired
    public MovieRecommender(CustomerPreference customerPreference) {
        this.customerPreference = customerPreference;
    }

    // ...
}

@Component
public class CustomerPreference {...}

(示例取自官方的Spring文档https://docs.spring.io/spring-framework/docs/4.3.x/spring-framework-reference/htmlsingle/#beans-autowired-annotation,这些文档根本没有显示@Component,这可能意味着它不需要,或者只是没有显示。)

我工作的项目不使用任何XMLBean声明,但它使用的框架不仅仅是Spring,因此有可能有什么东西将类声明为bean。或者它可能是我们使用的Spring版本的一个特性,如果该特性没有被记录,那么它可能会在以后被删除

问题: 使用@Autowired的类必须用@Component注释(当然,是bean)吗?有关于这方面的官方文件吗

UPD各位,项目中没有@Configuration和XML配置,我知道这样的声明从类生成bean,但问题不在于它们。我甚至在上面的问题中写了“(好吧,做一个豆子),来说明这一点。@Autowired在不是bean的类中工作吗?或者它声明了将其用作bean的类


共 (2) 个答案

  1. # 1 楼答案

    有几种方法可以在Spring中实例化bean
    其中一个是带有@Component注释的,有了它,Spring将扫描为组件扫描定义的所有包,并初始化所有带注释的类(使用@Component或使用它的一个注释-控制器、服务等)

    初始化bean的另一种方法是使用配置类(用@Configuration注释),该类包括用@Bean注释的方法。这些方法中的每一个都将创建一个bean

    还有一个使用xml配置创建bean的选项,但是这越来越不常见,因为基于注释的方法更加方便

  2. # 2 楼答案

    根据https://stackoverflow.com/a/3813725/755804,通过autowireBean()可以从未声明为bean的类中自动连接bean

    @Autowired
    private AutowireCapableBeanFactory beanFactory;
    
    public void sayHello(){
        System.out.println("Hello World");
        Bar bar = new Bar();
        beanFactory.autowireBean(bar);
        bar.sayHello();
    }
    

    package com.example.demo;
    
    import org.springframework.beans.factory.annotation.Autowired;
    
    public class Bar {
        @Autowired
        private Foo foo;
    
        public void sayHello(){
            System.out.println("Bar: Hello World! foo="+foo);
        }
    }
    

    另一方面,默认情况下,最新的Spring不假定使用@Autowire的类是@Component-s

    UPD 至于提到的实际项目,堆栈跟踪显示构造函数是从createBean()调用的。也就是说,框架从框架的配置中声明的类创建bean