plz*_*lme 29 java spring spring-boot
.yml文件
cassandra:
keyspaceApp:junit
solr:
keyspaceApp:xyz
Run Code Online (Sandbox Code Playgroud)
豆
@Component
@ConfigurationProperties(prefix="cassandra")
public class CassandraClientNew {
@Value("${keyspaceApp:@null}") private String keyspaceApp;
Run Code Online (Sandbox Code Playgroud)
主方法文件
@EnableAutoConfiguration
@ComponentScan
@PropertySource("application.yml")
public class CommonDataApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(CommonDataApplication.class)
.web(false).headless(true).main(CommonDataApplication.class).run(args);
}
}
Run Code Online (Sandbox Code Playgroud)
测试用例
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = CommonDataApplication.class)
@IntegrationTest
@EnableConfigurationProperties
public class CassandraClientTest {
@Autowired
CassandraClientNew cassandraClientNew;
@Test
public void test(){
cassandraClientNew.getSession();
System.out.println(" **** done ****");
}
}
Run Code Online (Sandbox Code Playgroud)
它不是将junit设置为keyspaceApp,而是设置xyz.
看起来像prefix ="cassandra"无效
Tom*_*Tom 51
您似乎正在尝试使用Spring Boot Typesafe配置属性功能.
因此,为了使其正常工作,您必须为代码添加一些更改:
首先,你的CommonDataApplication班级应该有@EnableConfigurationProperties注释,例如
@EnableAutoConfiguration
@ComponentScan
@PropertySource("application.yml")
@EnableConfigurationProperties
public class CommonDataApplication {
public static void main(String[] args) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
我不认为你需要@PropertySource("application.yml")注释,因为application.yml(以及application.properties和application.xml)是Spring Boot使用的默认配置文件.
您的CassandraClientNew类不需要具有@Value注释前缀keyspaceApp属性.你keyspaceApp 必须有一个setter方法.
@Component
@ConfigurationProperties(prefix="cassandra")
public class CassandraClientNew {
private String keyspaceApp;
public void setKeyspaceApp(final String keyspaceApp) {
this.keyspaceApp = keyspaceApp;
}
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果您使用List的是s或者Set初始化集合(例如List<String> values = new ArrayList<>();),那么只需要getter.如果未初始化集合,则还需要提供setter方法(否则将抛出异常).
我希望这会有所帮助.
# In application.yaml
a:
b:
c: some_string
Run Code Online (Sandbox Code Playgroud)
# In application.yaml
a:
b:
c: some_string
Run Code Online (Sandbox Code Playgroud)
确保在上述类中声明了这些公共方法。确保他们有“public”修饰符。
// In MyClassA
public void setTheB(MyClassB theB) {
this.theB = theB;
}
// In MyClassB
public void setTheC(String theC) {
this.theC = theC;
}
Run Code Online (Sandbox Code Playgroud)