首页 > 应用开发 > IT综合 > 教你如何使用Springboot注入带参数的构造函数
|
这篇文章主要介绍了使用Springboot注入带参数的构造函数实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
|
我们使用@Service注解一个service,默认注入的是不带参的构造函数,如果我们需要注入带参的构造函数,怎么办?
@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 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注入带参数的构造函数实例就是小编分享给大家的全部内容了,希望能给大家一个参考。
原文地址: https://www.linuxprobe.com/springboot-linux-service.html
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31559985/viewspace-2691468/ ,如需转载,请注明出处,否则将追究法律责任。