Spring Boot use component in a custom class? [closed]
I have a redis util :
@Component
public class RedisUtil {
@Autowired
private StringRedisTemplate stringRedisTemplate;
public StringRedisTemplate getStringRedisTemplate() {
return this.stringRedisTemplate;
}
}
I want to use it in my custom class which I don't want to be a component .
public class UserFeature {
public String result;
public String someMethod(){
var redisUtil = new RedisUtil();
var stringRedisTemplate = redisUtil.getStringRedisTemplate();
...
this.result = query_result_from_stringRedisTemplate;
}
}
When I use it like above , it raises a bean error . What should I do ?
Solution 1:
If you have a good reason for creating objects which shouldn't be spring-managed, but still need to use spring beans, you can create a factory component which does the injection of spring beans into your non-spring object.
@Component
class UserFeatureFactory {
private final RedisUtil redisUtil;
@Autowired
public UserFeatureFactory(RedisUtil redisUtil) { ... }
public UserFeature createUserFeature() {
return new UserFeature(redisUtil);
}
}
// no spring annotations
class UserFeature {
...
public UserFeature(RedisUtil redisUtil) {
this.redisUtil = redisUtil
}
...
}
One nice feature of this approach is that it makes UserFeature
easy to test -- you can just pass its constructor a mock RedisUtil
.