您的位置:首页 > 编程语言 > Java开发

使用Springboot注入带参数的构造函数实例

2020-04-27 12:04 4894 查看

我们使用@Service注解一个service,默认注入的是不带参的构造函数,如果我们需要注入带参的构造函数,怎么办?

使用@Configuration+ @Bean注解来实现注入:

@Configuration
public class BlockChainServiceConfig {

@Bean
BlockChainService blockChainService(){
return new BlockChainService(1);
}
}

service类

public class BlockChainService {

private int number;
public BlockChainService(int number) {

this.number=number;

}
}

补充知识:Spring Boot - Spring Beans之依赖构造器注入

使用所有Spring Framework技术定义的beans以及他们的依赖注入都是免费的。简单起见,我们通常使用@CompnentScan查找beans,结合@Autowired构造注入效果比较好。

如果你的代码结构是按之前建议的结构(将应用类放到根包里),你可以添加@ComponentScan,不需要任何参数。这样你所有的应用组件(@Component,@Service,@Repository,@Controller等等)都将会注册为Spring Beans。

看下面的例子,@Service Bean使用构造注入,获取CacheManager bean。

package com.example.service;

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

@Service
public class DatabaseCacheService implements CacheService {

private final CacheManager cacheManager;

@Autowired
public DatabaseCacheService(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}

// ...

}

如果这个bean有一个构造,可以省略@Autowired。

@Service
public class DatabaseCacheService implements CacheService {

private final CacheManager cacheManager;

public DatabaseCacheService(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}
// ...

}

注意,使用构造注入允许cacheManager标记为final,这也表示以后不能再被更改了。

以上这篇使用Springboot注入带参数的构造函数实例就是小编分享给大家的全部内容了,希望能给大家一个参考

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息