成员变量的注入是在Bean创建成功之后,通过setter方法进行注入的。所以下面会获取不到值
@RestController public class VipsoftImController { @Autowired private ZooKeeperUtil zooKeeperUtil; @RequestMapping("/") public String index() { return StrUtil.format("Hello World"); } } @Component public class ZooKeeperUtil { private static final Logger logger = LoggerFactory.getLogger(ZooKeeperUtil.class); @Value("${zookeeper.connectString}") private String connectString; public ZooKeeperUtil() { System.out.println(connectString); //值为Null } }
解决方案:
@RestController public class VipsoftImController { @Autowired private ZooKeeperUtil zooKeeperUtil; @RequestMapping("/") public String index() { return StrUtil.format("Hello World"); } } @Component public class ZooKeeperUtil { private static final Logger logger = LoggerFactory.getLogger(ZooKeeperUtil.class); private String connectString; public ZooKeeperUtil(@Value("${zookeeper.connectString}") String conn) { this.connectString = conn; System.out.println(connectString); } }
属性多的话应该可以用一个类 @ConfigurationProperties(prefix = "xxxxx") 做为参数,没试过
在yml里面加入我们的自定义配置项,如(注意,使用一开始的key参数使用小写,使用大写会出错,因为prefix不支持驼峰命名和下划线形式)