美文网首页
springboot2.2.6.RELEASE chapter4

springboot2.2.6.RELEASE chapter4

作者: 淼哥1986 | 来源:发表于2020-04-03 20:25 被阅读0次

您可以自由使用任何标准的Spring框架技术来定义bean及其注入的依赖项。为了简单起见,我们经常发现使用@ComponentScan(来查找bean)和使用@Autowired(来进行构造函数注入)可以很好地工作。

如果按照上面的建议构造代码(在根包中定位应用程序类),则可以添加@ComponentScan而无需任何参数。所有应用程序组件(@Component,@Service,@Repository,@Controller等)都自动注册为springbean。

以下示例显示了一个@Service Bean,它使用构造函数注入来获取所需的RiskAssessor Bean:

The following example shows a @Service Bean that uses constructor injection to obtain a required RiskAssessor bean:

package com.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DatabaseAccountService implements AccountService {

    private final RiskAssessor riskAssessor;

    @Autowired
    public DatabaseAccountService(RiskAssessor riskAssessor) {
        this.riskAssessor = riskAssessor;
    }

    // ...

}

If a bean has one constructor, you can omit the @Autowired, as shown in the following example:

@Service
public class DatabaseAccountService implements AccountService {

    private final RiskAssessor riskAssessor;

    public DatabaseAccountService(RiskAssessor riskAssessor) {
        this.riskAssessor = riskAssessor;
    }

    // ...

}

Notice how using constructor injection lets the riskAssessor field be marked as final, indicating that it cannot be subsequently changed.

相关文章

网友评论

      本文标题:springboot2.2.6.RELEASE chapter4

      本文链接:https://www.haomeiwen.com/subject/zvzkphtx.html