说起这件事还是有点小插曲,一个刚来不久的同事问起了这个问题,看了下没问题啊,是不是注入方式不对呢?或者configuration根本就没有注入进来?当场没有解决,这个耿直BOY竟然说我水,哎老脸往哪搁。记录下:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import javax.sql.DataSource;
@Configuration
public class MyConfigFactory {
// 该方式在ConfigurationProperties注解在类上可直接获取,因此可定义一个属性类做映射来获取配置文件。这种取值方式是可以取到的,而ConfigurationProperties注解在如下方法的DataSource=null
@Value("${spring.datasource.username}")
private String username;
public String getUsername() {
return username;
}
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource", ignoreInvalidFields = true)
public DataSource getDataSource(){
DataSource dataSource = DataSourceBuilder.create().build();
return dataSource;
}
}
确实该处取值的datasource=null,原因是config还没有注入进来,但是我用RestController请求之后,使用Autowried注入Service后即可取到了。
==================Service方法=========================
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
@Service
public class MyDataSourceService {
@Autowired
MyConfigFactory myConfigFactory;
public void getDataSource(){
DataSource dataSource = myConfigFactory.getDataSource();
System.out.println(dataSource);
}
}
==================Controller方法=========================
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Autowired
private MyDataSourceService myDataSource;
@RequestMapping(value = "/info", method = RequestMethod.GET)
public String getInfo(){
myDataSource.getDataSource();
return "AAAAA";
}
}
接口请求后,发现DataSource可获得数据源了。我想这种类似于事务补偿机制吧?后续填值得方式。而后我使用实体bean得注入方式尝试看看是否能提前获取到呢?
结果呢!并没有奇迹,启动时查看还是为null,而后请求时才获得配置文件得结果。因此可推算该属性是lazy性质。使用之前得好好考虑是否可容许这种方式。
具体的ConfigurationProperties注入方式等后续研究到该部分再详细说明吧。