Java 避免@Autowired字段为空

Java 避免@Autowired字段为空,java,spring-boot,Java,Spring Boot,我正在将项目迁移到Spring Boot,并且我有订阅服务。class: @Component public class SubscriptionService { @Autowired @Qualifier("dms") private RestTemplate restTemplate; @Autowired private DmsModule module; @Autowired public Subscr

我正在将项目迁移到Spring Boot,并且我有订阅服务。class

@Component
public class SubscriptionService {

    @Autowired
    @Qualifier("dms")
    private RestTemplate restTemplate;
    
    @Autowired
    private DmsModule module;

 @Autowired
    public SubscriptionService(MoveInformation moveInformation, Set<WorkShopEvent> events) {
        if (moveInformation == null) {
            throw new IllegalArgumentException("Move Information is null.");
        }

        moveInfo = moveInformation;

        if (events != null) {
            workShopEvents.addAll(events);
        }
    }

public static Set<SubscriptionService> createSubscriptionServices(DmsModule config,
            Map<String, MoveInformation> move) {
        Set<SubscriptionService> services = new HashSet<>();

        List<ModuleMove> moduleMoves = config.getMove();

        for (ModuleMove md : moduleMoves) {
            MoveInformation moveInfo = move.get(md.getMoveRef());

            List<String> events = md.getSubscriptions();
            Set<WorkShopEvent> workShopEvents = parseEvents(events);

            if (moveInfo != null && !workShopEvents.isEmpty()) {
                SubscriptionService service = new SubscriptionService(moveInfo, workShopEvents);

                services.add(service);
            } else {
                ...// some stuff
                }
            }
        }
        return services;
    }
}
@组件
公共类订阅服务{
@自动连线
@限定词(“dms”)
私有RestTemplate RestTemplate;
@自动连线
专用模块;
@自动连线
公共订阅服务(移动信息、移动信息、设置事件){
if(moveInformation==null){
抛出新的IllegalArgumentException(“移动信息为空”);
}
moveInfo=moveInformation;
如果(事件!=null){
workShopEvents.addAll(事件);
}
}
公共静态集合createSubscriptionServices(DMS模块配置,
地图移动){
Set services=newhashset();
List modulemove=config.getMove();
for(ModuleMove md:ModuleMove){
MoveInformation moveInfo=move.get(md.getMoveRef());
List events=md.getSubscriptions();
设置workShopEvents=parseEvents(事件);
if(moveInfo!=null&&!workShopEvents.isEmpty()){
SubscriptionService服务=新的SubscriptionService(moveInfo、workShopEvents);
服务。添加(服务);
}否则{
…一些东西
}
}
}
返回服务;
}
}

subscriptionservice.class不是由Spring上下文初始化的,而是由new创建的,
restTemplate
module
字段为空。如何避免呢?
restemplate
module
字段的bean被创建,并且在SpringBeans
@Configuration
类中初始化的
@Service
类中不返回null。

“subscriptionservice.class不是由Spring上下文初始化的,而是由new创建的”-这是您的答案。注释并不神奇,它们只是其他代码可以使用的元数据。如果没有使用Spring创建对象,然后,该类所做的就是您在构造函数中指定它应该做的事情,或者您想用它做什么?让Spring创建
SubscriptionService
?然后我必须将createSubscriptionServices方法移动到bean?您可以将创建它们的方法移动到配置类?不确定,因为工厂方法返回一个集合