【问题标题】:Whats bean in spring and what is not什么是春天的豆,什么不是
【发布时间】:2017-02-28 19:07:44
【问题描述】:

假设我有这样的代码:

@Repository
public class Foo{
}

@Service
public class Boo{

@Autowired
private Foo foo;
}

那么现在我们在这里称什么为 bean? Bean 是 Foo 类型的引用“foo”的对象,但是 Boo 类被注释为 Service 和 Foo 作为 Repository ALSO bean?我已经使用 spring 一段时间了,但是这个基本问题让我因为不知道而感到难过......

【问题讨论】:

标签: spring


【解决方案1】:

您的所有应用程序组件(@Component、@Service、@Repository、@Controller 等)都将自动注册为 Spring Beans

http://docs.spring.io/autorepo/docs/spring-boot/current/reference/html/using-boot-spring-beans-and-dependency-injection.html

【讨论】:

    【解决方案2】:

    在 Spring 的上下文中,一个 bean 是一个 Spring 管理的对象。这里的spring managed是指由Spring IoC容器创建、初始化、管理、销毁的对象。

    每当我们用@Component 标记一个类时,Spring IOC 容器将为您的类创建对象并管理它,只要我们可以从ApplicationContext 简单地获取它,或者使用@Autowired/@Resource/@Inject 注释访问它

    我们还可以使用@Controller, @Repository, @Service, @ControllerAdvice, @Configuration,@Aspect 代替@Component 来更具体地说明我们的类是服务或存储库或方面等。

    我们也可以使用@Bean注解从方法返回值创建一个bean

    @Configuration
    public class SolrConfig {
    
        @Value("${spring.data.solr.host}") String solrUrl;
    
        @Bean
        public SolrServer solrServer() {
            return new HttpSolrServer(solrUrl);
        }
    
        @Bean(name = "solrTemplate")
        public SolrTemplate solrTemplate() {
            return new SolrTemplate(new HttpSolrServer(solrUrl), RULE_ENGINE_CORE);
        }
    }
    

    【讨论】:

      【解决方案3】:

      定义 Bean 可以认为是替换关键字 new。

      可以在here 找到更多信息,这可能有助于理解 Spring 中的 Bean。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-30
        • 2013-01-23
        • 2011-04-01
        • 2021-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多