Can not read properties file based on active profile - java

Hello java programmers,
I have a problem with reading the properties file based on active profile. I have created a spring boot application and I would like to deploy my application for different environments such as development and production. I have searched quit a lot, but I could not find a solution for my problem.
I have set a profile in the edit configuration menu.
I have a properties file called application-dev.properties in my src/main/resources and I have a Settings.java where I would like to read the properties file.
This is my Settings.java
#Configuration
#Component
public class Settings {
private static Logger log = Logger.getLogger(Settings.class);
#Value("${TradingBot.production}")
public boolean isProduction;
#Value("${api.KEY}")
public static String API_KEY;
#Value("${api.ORDERS_URL}")
public static String ORDERS_URL;
#Value("${api.TRADES_URL}")
public static String TRADES_URL;
#Value("${api.PARTICIPANTS_URL}")
public static String PARTICIPANTS_URL;
#Value("${api.INDIVIDUAL_URL}")
public static String INDIVIDUAL_URL;
#Value("${api.BALANCE_URL}")
public static String BALANCE_URL;
#Value("${api.TRANSACTIONS_URL}")
public static String TRANSACTIONS_URL;
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){
return new PropertySourcesPlaceholderConfigurer();
}
}
According to the spring documentation this should be enough to read the correct properties file, unfortunately I get an empty String when I print the value.
When I run the project it will give me the following output.
2016-10-31 13:44:04.011 INFO 32992 --- [ main] TradingBot : The following profiles are active: dev
I hope someone can help me.

Thanks to M.Denium I knew what the problem was. I could solve it by adding the #Value property at the setter for Example:
public static String API_KEY;
public static String ORDERS_URL;
public static String TRADES_URL;
public static String PARTICIPANTS_URL;
public static String INDIVIDUAL_URL;
public static String BALANCE_URL;
public static String TRANSACTIONS_URL;
#Value("${api.KEY}")
public void setAPI_KEY(String API_KEY) {
this.API_KEY = API_KEY;
}
#Value("${api.ORDERS_URL}")
public void setORDERS_URL(String ORDERS_URL) {
this.ORDERS_URL = ORDERS_URL;
}
#Value("${api.TRADES_URL}")
public void setTRADES_URL(String TRADES_URL) {
this.TRADES_URL = TRADES_URL;
}
#Value("${api.PARTICIPANTS_URL}")
public void setPARTICIPANTS_URL(String PARTICIPANTS_URL) {
this.PARTICIPANTS_URL = PARTICIPANTS_URL;
}
#Value("${api.INDIVIDUAL_URL}")
public void setINDIVIDUAL_URL(String INDIVIDUAL_URL) {
this.INDIVIDUAL_URL = INDIVIDUAL_URL;
}
#Value("${api.BALANCE_URL}")
public void setBALANCE_URL(String BALANCE_URL) {
this.BALANCE_URL = BALANCE_URL;
}
#Value("${api.TRANSACTIONS_URL}")
public void setTRANSACTIONS_URL(String TRANSACTIONS_URL) {
this.TRANSACTIONS_URL = TRANSACTIONS_URL;
}
In this case the variable will still be static and it can get the value from the property file.

Related

How to combine two environment variable in #Value annotation

I have application.yaml as following
environment: ${ZK_ENVIRONMENT}
END_POINT_URL:
dev: http://sampledev.uk.com
qa: http://sampleqa.uk.com
prod: http://sampleprod.uk.com
environment values can be dev,qa or prod. I need o inject END_POINT_URL based on environment in #Value.Tried the following, it's not working.
#Value("${END_POINT_URL}.${environment}")
private String url;
This should work, just did a quick test as well
#Value("${END_POINT_URL.${environment}}")
#SpringBootApplication
public class DemoApplication {
#Value("${END_POINT_URL.${environment}}")
private String value;
#PostConstruct
public void init() {
System.out.println(value);
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
ZK_ENVIRONMENT:dev
Output : http://sampledev.uk.com

Adding new custom properties in Kafka Connect

I am trying to add new custom Kafka Converter which is a modification of JsonConverterConfig in connect-json. I am trying to add some new custom property say "schemas.modifications.enable" in the converter which extends JsonConverterConfig. But Kafka connect is not able to find details about the converter.
My code Snippet :
public class ModifiedJsonConfig extends JsonConverterConfig {
public static final String SCHEMAS_MODIFY_CONFIG = "schemas.modifications.enable";
public static final boolean SCHEMAS_MODIFY_CONFIG_DEFAULT = true;
private static final String SCHEMAS_MODIFY_CONFIG_DOC = "The maximum number of schemas that can be cached in this converter instance.";
private static final String SCHEMAS_MODIFY_CONFIG_DISPLAY = "Schema Cache Size";
private final static ConfigDef CONFIG;
static {
String group = "Schemas-modification";
int orderInGroup = 0;
CONFIG = ConverterConfig.newConfigDef();
CONFIG.define(SCHEMAS_MODIFY_CONFIG, Type.BOOLEAN, SCHEMAS_MODIFY_CONFIG_DEFAULT, Importance.HIGH, SCHEMAS_MODIFY_CONFIG_DOC, group,
orderInGroup++, Width.MEDIUM, SCHEMAS_MODIFY_CONFIG_DISPLAY);
}
public static ConfigDef configDef() {
return CONFIG;
}
public ModifiedJsonConfig(Map<String, ?> props) {
super(props);
}
public boolean schemasModified() {
return getBoolean(SCHEMAS_MODIFY_CONFIG);
}
}
But I am getting the error here :
ERROR Stopping due to error (org.apache.kafka.connect.cli.ConnectDistributed:83)
org.apache.kafka.common.config.ConfigException: Unknown configuration 'schemas.modifications.enable'
But I have defined this configuration. It would be really helpful if you can help me set a custom converter property here.
Thanks in advance.

Why can't I access application.properties values outside of my #SpringBootApplication-annotated main file?

I have a custom defined key-value pair in my Spring Boot application.properties file:
jwt.secret=secretkey
I've created a configuration class for this property in the same directory as the runner class:
#Configuration
#ConfigurationProperties(prefix = "jwt")
#PropertySource("classpath:application.properties")
public class JwtProperties {
/**
* Secret key used to sign JSON Web Tokens
*/
private String secret = "";
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
}
As expected, I can access this value in my main Spring runner class, ServerApplication.java using the #Value annotation:
#SpringBootApplication
#EnableConfigurationProperties(JwtProperties.class)
public class ServerApplication implements CommandLineRunner {
#Value("${jwt.secret}")
String test;
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
// correctly prints "test is: secretkey"
System.out.println("test is " + test);
}
}
I have a class /security/JwtClient.java where I'd like to be able to use this jwt.secret property, but I can't get the #Value annotation to work (it always results in a null String):
#Component
public class JwtClient {
#Value("${jwt.secret}")
private String secretKey;
public String buildJWT(Customer customer) {
// incorrectly prints "secret key: null"
System.out.println("secret key: " + secretKey);
// attempts to build JSON Web Token here but secret key is missing
}
}
I've read many StackOverflow questions on this topic, but almost all of them seem to assume that the #Value annotation will work properly on a #Component-annotated class. What am I missing here?

Spring boot #Value is null

Before we start, yes I know there's another question out there but they are not the same issue and I couldn't find anything to solve this.
Ok, I have
package a
imports ...
#SpringBootApplication
public class LauncherApplication implements CommandLineRunner {
#Autowired
private SubListener subListener;
#Value("${proj.id}")
private String testy;
public static void main(String[] args) {
SpringApplication.run(LauncherApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println(subListener.getProjID());
System.out.println(testy);
}
}
Then on my subListener
package a.b
imports ...
#Component
public class SubListener {
#Value("${proj.id}")
private String projID;
public String getProjID() {
return projID;
}
}
and finally inside my resources folder on application.properties
proj.id=Hello from file
Now, by all accounts this should work, the SpringBootApplication has the component scan thing, the bean is marked as #component and is a subpackage of the springbootapplication, the properties file has the default name and in the default directory. I can't find a single reason for this not to work. Also mind you that when I call the property on testy it works, it only return null when it's returning from the sublistener.
Thank you for your time
EDIT:
New launcherApplication
#SpringBootApplication
public class LauncherApplication {
public static void main(String[] args) {
SpringApplication.run(LauncherApplication.class, args);
}
#Bean
public CommandLineRunner runner(SubListener subListener){
CommandLineRunner runner = new CommandLineRunner() {
#Override
public void run(String... args) throws Exception {
System.out.println(subListener.getProjID());
}
};
return runner;
}
}
It still returns null though
My only guess would be that the #Value annotation inside your SubListener class is from the wrong package. Can you please check that you are using this import and not something else:
import org.springframework.beans.factory.annotation.Value;
I've copied your code and it's working for me. If you still can't get it working then I'd recommend trying to reproduce it in a new empty project.

Spring Boot : How to get program args with ConfigurationProperties

I'm trying to get some properties from the command line when I start my app. I really try a lot of solution but nothings is working. I'll only use #Value as a last solution
java -jar myjar.jar --test.property=something
Here's some classes
Main class
#SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(TestApplication.class);
builder.run(args);
}
}
Config class
#Configuration
#EnableConfigurationProperties(StringProperties.class)
public class StringConfiguration {
#Autowired
private StringProperties stringProperties;
#Bean(name = "customBeanName")
public List<String> properties() {
List<String> properties = new ArrayList<>();
properties.add(stringProperties.getString());
return properties;
}
}
Properties class
#Component
#ConfigurationProperties("test")
public class StringProperties {
private String property;
public String getString() {
return property;
}
}
Ops.....I have tested your code.It is setProperty that missed in StringProperties.
public void setProperty(String property) {
this.property = property;
}

Categories