| 知乎专栏 |
@Autowired
private TestService testService;
当我们使用 @Autowired 注解,构造方法先于 @Value 执行,所以我们无法在构造方法中获得 @Value 注入的值。
package cn.netkiller.services;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
@Data
@Slf4j
public class TestService {
@Value("${app.id}")
private String appId;
public TestService() {
log.info(this.appId);
}
}
@Value 作为构造方法的参数可以实现赋值需求
package cn.netkiller.services;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
@Data
@Slf4j
public class TestService {
private String appId;
public TestService(@Value("${app.id}") String appId) {
this.appId = appId;
log.info(this.appId);
}
}
同时还能使用 new 创建实例
TestService test = new TestService("Test");
test.getAppId();