Spring Bean和依赖注入

你可以自由使用任何标准的Spring框架技术来定义bean及其注入的依赖关系.为了简单起见,可以使用@ComponentScan找到你的bean,结合@Autowired构造函数注入.

如果你像上面建议的哪有构造代码(在根包中定位你的应用),你可以添加任何参数的@ComponentScan。所有的应用程序组件(@Component,@Service,@Repository,@Controller)将被自动注解为Spring Bean.

下面是一个使用构造函数注入来获取所需的RiskAssessor bean的示例@Service 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;
        }

        // ...

    }

使用构造函数注入,允许将参数riskAssessor修饰为final,表示不能在随后的代码中更改

Copyright © www.gitbook.com/@herryZ 2016 all right reserved,powered by Gitbook该文件修订时间: 2017-01-06 08:13:12

results matching ""

    No results matching ""