在Spring Boot的构造函数中是否强制使用@Autowired批注

@Autowired如果我使用构造函数DI,是否必须填写?

回答:

@Autowired注释对于构造函数是必需的吗?

Spring 4.3之后,如果您的类只有单个构造函数,则无需放置@Autowired

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;

}

// ...

}

@Service

public class DatabaseAccountService implements AccountService {

private final RiskAssessor riskAssessor;

public DatabaseAccountService(RiskAssessor riskAssessor) {

this.riskAssessor = riskAssessor;

}

// ...

}

以上是 在Spring Boot的构造函数中是否强制使用@Autowired批注 的全部内容, 来源链接: utcz.com/qa/407344.html

回到顶部