使用SpringBoot,我正在学习简单的课程
@Component
@PropertySource("server.properties")
public class CoreFacade {
private static final Logger log = Logger.getLogger(CoreFacade.class);
@Value("${chat.server.port}")
private int port;
private Server server;
public CoreFacade() {
log.info(String.valueOf(port));
server = new Server(port);
}
}
,在src / main / resources下,我得到了server.properties与
chat.server.port = 9999
但最终以
记录INFO 2018-08-20 21:48:02,878 [main] com.example.chatserver.core.CoreFacade [] []-0
而不是9999
任何想法在这里可能出什么问题吗?
答案 0 :(得分:0)
您将类注释为Spring组件。
在对bean进行任何依赖项注入之前,Spring会在构造函数被Spring调用时打印0
。
您需要将此类声明为配置类,例如:
@Configuration
@PropertySource("server.properties")
public class CoreFacade {
...
}
如果有道理,您可以使Server
是在类中定义的bean,例如:
@Value("${chat.server.port}")
private int port;
@Bean
public Server server() {
return new Server(port);
}
答案 1 :(得分:0)
davidxxx提出的另一种解决方案是将构造函数标记为@Autowired:
@Component
@PropertySource("server.properties")
public class CoreFacade {
private static final Logger log = Logger.getLogger(CoreFacade.class);
private Server server;
@Autowired
public CoreFacade(
@Value("${chat.server.port}")
int port
) {
log.info(String.valueOf(port));
server = new Server(port);
}
}
您还可以使用@PostConstruct,它在@Value解析之后调用:
@Component
@PropertySource("server.properties")
public class CoreFacade {
private static final Logger log = Logger.getLogger(CoreFacade.class);
@Value("${chat.server.port}")
private int port;
private Server server;
@PostConstruct
public void postConstruct() {
log.info(String.valueOf(port));
server = new Server(port);
}
}