Spring Accessing configuration - AlreadyBuiltException when setting variable using #Value - spring

I am implementing ldap authentication using Spring Security. It works when I hardcode all the ldap server information in following configuration class.
//WebSecurityConfig.java
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin();
}
#Configuration
protected static class AuthenticationConfiguration extends
GlobalAuthenticationConfigurerAdapter {
#Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource("ldap://ldap.mdanderson.edu:389/dc=mdanderson,dc=edu");
contextSource.setUserDn("cn=ris_flow,ou=service accounts,ou=institution,ou=service accounts,dc=mdanderson,dc=edu");
contextSource.setPassword("xxxyyyzzz");
contextSource.setReferral("follow");
contextSource.afterPropertiesSet();
LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder> ldapAuthenticationProviderConfigurer = auth.ldapAuthentication();
ldapAuthenticationProviderConfigurer
.userDnPatterns("cn={0},ou=institution,ou=people")
.userSearchBase("")
.contextSource(contextSource);
}
}
}
I decided to put these server information in application.properties and set the variables using #Value in my config class, so I add the following right before AuthenticationConfiguration.
#Value("${ldap.contextSource.url")
private static String url;
#Value("${ldap.contextSource.managerDn")
private static String userDn;
#Value("${ldap.contextSource.managerPass")
private static String userPass;
And replaced the lines of contextSource to:
DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(url);
contextSource.setUserDn(userDn);
contextSource.setPassword(userPass);
However when I ran it again, the application failed to start with errors below:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource.......
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate....
Caused by: java.lang.IllegalArgumentException: An LDAP connection URL must be supplied.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource....
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate....
Caused by: org.springframework.security.config.annotation.AlreadyBuiltException: This object has already been built
What did I do wrong?

Check this piece of code
#Value("${ldap.contextSource.url")
private static String url;
#Value("${ldap.contextSource.managerDn")
private static String userDn;
#Value("${ldap.contextSource.managerPass")
private static String userPass;
You need to close the brackets properly this way
#Value("${ldap.contextSource.url}") private static String url;
#Value("${ldap.contextSource.managerDn}") private static String userDn;
#Value("${ldap.contextSource.managerPass}") private static String userPass;
From Spring In Action Fourth Edition book:
When relying on component-scanning and autowiring to create and initialize your
application components, there’s no configuration file or class where you can specify the placeholders. Instead, you can use the #Value annotation in much the same way as you might use the #Autowired annotation.
In order to use placeholder values, you must configure either a PropertyPlaceholderConfigurer bean or a PropertySourcesPlaceholderConfigurer bean. Starting with Spring 3.1, PropertySourcesPlaceholderConfigurer is preferred because it resolves placeholders against the Spring Environment and its set of property sources.
The following #Bean method configures PropertySourcesPlaceholderConfigurer
in Java configuration:
#Bean
public
static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
EDIT: Complete example accesing properties using SPRING 4.2.5 RELEASE
Configuration Class:
#Configuration
#ComponentScan
#PropertySource("classpath:/your/package/example.properties")
// In my case, this package is stored in src/main/resources folder, which is in the classpath of the application
public class SpringPropertiesConfig {
#Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
Component (Bean) accessing the properties:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
#Component
public class ComponentAccessingProperties {
#Value("${first.property}")
private String propertyOne;
#Value("${second.property}")
private String propertyTwo;
public String getPropertyOne() {
return propertyOne;
}
public String getPropertyTwo() {
return propertyTwo;
}
}
Example properties file (/your/package/example.properties):
first.property=ONE
second.property=SECOND
Test Class:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import your.package.ComponentAccessingProperties;
import your.package.SpringPropertiesConfig;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = SpringPropertiesConfig.class)
public class TestAccessingProperties {
#Autowired
private ComponentAccessingProperties componentAccesingProperties;
#Test
public void shouldNotBeNull() {
assertNotNull(componentAccesingProperties);
}
#Test
public void checkProperties() {
assertEquals("ONE", componentAccesingProperties.getPropertyOne());
assertEquals("SECOND", componentAccesingProperties.getPropertyTwo());
}
}

Related

Spring interface injection from external jar

I have spring API based authentication classes in external library,
Below are some of the classes in external library,
package com.security;
import org.springframework.security.authentication.AuthenticationProvider;
#Component
public class ApiKeyAuthenticationProvider implements AuthenticationProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(ApiKeyAuthenticationProvider.class);
private ApiAuthCredentialsConfig apiAuthCredentialsConfig;
public ApiKeyAuthenticationProvider(ApiAuthCredentialsConfig apiAuthCredentialsConfig) {
this.apiAuthCredentialsConfig = apiAuthCredentialsConfig;
}
}
ApiAuthCredentialsConfig:
package com.security;
public interface ApiAuthCredentialsConfig {
String getAuthToken();
String getAuthTokenHeaderName();
}
And in the repo I have added the above external library as a gradle dependency.
I have below changes in actual repo.
#Component
#Data
public class ApiAuthenticationConfig implements ApiAuthCredentialsConfig {
#Value("${auth-token}")
private String authToken;
#Value("${auth-token-header-name}")
private String authTokenHeaderName;
}
SecurityConfig:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private ApiKeyAuthenticationProvider apiKeyAuthenticationProvider;
#Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.
antMatcher("/**").
csrf().disable().
sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
and().addFilterBefore(new ApiKeyAuthenticationFilter(authenticationManager(), apiKeyAuthenticationProvider.getHeaderName()), AnonymousAuthenticationFilter.class)
.authorizeRequests().anyRequest().authenticated();
}
#Bean
public AuthenticationManager authenticationManager() {
return new ProviderManager(Collections.singletonList(apiKeyAuthenticationProvider));
}
}
Application:
#SpringBootApplication(scanBasePackages = {"com.security"})
#EnableSwagger2
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
When I run the application its failing with below error
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.security.ApiKeyAuthenticationProvider required a bean of type 'com.security.ApiAuthCredentialsConfig' that could not be found.
How to resolve this issue?
After the above comment, I realized that ApiAuthenticationConfig is not in the same package as ApiAuthCredentialsConfig, after I moved ApiAuthenticationConfig to com.security package it started working.

Spring can't find Autowired interface implementation

I have a main SpringBootApplication class here:
package com.example.springproj;
#SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
#RestController class here:
package com.example.springproj.controller;
#RestController
#Api("Sample")
public class RefDataController {
#Autowired
#Qualifier("RefDataServiceImpl")
private RefDataService refDataService;
#GetMapping(path = {"/refdata"}, produces = {"application/json"})
public ResponseEntity<Configuration> getRefData() {
// etc
}
}
The controller autowires this interface:
package com.example.springproj.service;
public interface RefDataService {
Configuration getConfiguration(String param);
}
Which is implemented by this class:
package com.example.springproj.services;
#Service
public class RefDataServiceImpl implements RefDataService {
#Autowired
private ConfigRepository config;
#Value("${ENV}")
private String environment;
#Override
public Configuration getConfiguration(String param) {
// etc
}
}
But when I run the App.java file, I get this
***************************
APPLICATION FAILED TO START
***************************
Description:
Field refDataService in com.citi.icrm.risk.springproj.controller.RefDataController required a bean of type 'com.citi.icrm.risk.springproj.service.RefDataService' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
- #org.springframework.beans.factory.annotation.Qualifier(value=RefDataServiceImpl)
Action:
Consider defining a bean of type 'com.citi.icrm.risk.springproj.service.RefDataService' in your configuration.
I'm reasonably sure that this auto-wiring should work, and I'm not sure how to go about configuring this bean in a Spring boot app. What am I doing wrong?
EDIT: Things I've already tried include:
Removing all of the #Qualifier annotations
#RestController
#Api("Sample")
public class RefDataController {
#Autowired
private RefDataServiceImpl refDataService;
#GetMapping(path = {"/refdata"}, produces = {"application/json"})
public ResponseEntity<Configuration> getRefData() {
System.err.println("testing.");
return new ResponseEntity<Configuration>(refDataService.getConfiguration("EEMS_USER_DETAIL_URL"), HttpStatus.OK);
}
}
public class RefDataServiceImpl implements RefDataService {
#Autowired
private ConfigRepository config;
#Value("${ENV}")
private String environment;
#Override
public Configuration getConfiguration(String param) {
try {
return config.getConfiguration(param, environment);
} catch (Exception e) {
e.printStackTrace();
throw (RuntimeException) new RuntimeException().initCause(e);
}
}
}
Changing the bean names to match convention
#RestController
#Api("Sample")
public class RefDataController {
#Autowired
#Qualifier("refDataServiceImpl")
private RefDataService refDataService;
#GetMapping(path = {"/refdata"}, produces = {"application/json"})
public ResponseEntity<Configuration> getRefData() {
System.err.println("testing.");
return new ResponseEntity<Configuration>(refDataService.getConfiguration("EEMS_USER_DETAIL_URL"), HttpStatus.OK);
}
}
#Service("refDataServiceImpl")
public class RefDataServiceImpl implements RefDataService {
#Autowired
private ConfigRepository config;
#Value("${ENV}")
private String environment;
#Override
public Configuration getConfiguration(String param) {
try {
return config.getConfiguration(param, environment);
} catch (Exception e) {
e.printStackTrace();
throw (RuntimeException) new RuntimeException().initCause(e);
}
}
}
For reference, the files fall into the app's package structure like so:
com.example.springproj
-> com.example.springproj.controller
--> RefDataController
-> com.example.springproj.services
--> RefDataService
-> com.exampple.springproj.services.impl
---> RefDataServiceImpl
Here's the folder structure, since some people have asked:
Firstly, you don't need #Qualifier("RefDataServiceImpl") if you have only one implementation of the RefDataService interface.
You just need
#Autowired
private RefDataService refDataService;
Secondly, the name of a bean generated on a class name but starts with a lowercase letter. In your example, the name of bean will look like refDataServiceImpl.
So, you can autowired this bean like below
#Autowired
#Qualifier("refDataServiceImpl")
private RefDataService refDataService;
Thirdly, you can specify the name of bean
#Service("youBeanName")
public class RefDataServiceImpl implements RefDataService
and then autowired this bean by the name in you controller, for example
#RestController
#Api("Sample")
public class RefDataController {
#Autowired
#Qualifier("youBeanName")
private RefDataService refDataService;
//....
}
Change the #Service annotation on the RefDataServiceImpl class as follows:
#Service("RefDataServiceImpl")
public class RefDataServiceImpl implements RefDataService
The #Qualifier name in the autowired service does not match a bean in your spring configuration.
The default naming convention is the full path of the class.
Because of this,
the name that Spring is probably using in your config for the RefDataServiceImpl service is this: "com.example.springproj.services.RefDataServiceImpl".
Added:
This page might be a good read: https://www.baeldung.com/spring-qualifier-annotation.
Attempt Two:
Try this
#Service
#Qualifier("RefDataServiceImpl")
#Service("RefDataServiceImpl")
public class RefDataServiceImpl implements RefDataService
I fixed the issue by putting RefDataServiceImpl in the same package as RefDataService.Before this I was keeping it in a sub-folder to the main services package. I'm still certain that I should be able to make this work with an implementation sub-folder, but this works as a solution for now.
I ran into this same issue while trying to implement a class with a database query. Adding #Repository to the top of the implemented class solved my problem.

Cannot inject property value to class parameter (#Value annotatnion)

I'm learing Spring Boot and I have probably very simple question, but it's not clear enough for me. I'm facing some problem with #Value annotation - I would like to know why apprication property cannot be injected to class parameter.
I prepared some very basic project using Spring Initializr and I added one property to my "application.properties" resource. Moreover, I created two additional classes: "YellowCar" (which works fine) and "RedCar" (which does not work - the parameter cannot be properly injected).
"application.properties" file:
car.age=15
The main class of my application:
package com.example.helper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
#SpringBootApplication
public class HelperApplication implements CommandLineRunner {
#Autowired
private Environment env;
public static void main(String[] args) {
SpringApplication.run(HelperApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println (new RedCar(env));
System.out.println (new YellowCar());
}
}
RedCar is build by passing the Environment variable to constructor:
package com.example.helper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
#Component
public class RedCar {
private int age;
#Autowired
public RedCar (Environment env) {
this.age = new Integer(env.getRequiredProperty("car.age")).intValue();
}
#Override
public String toString() {
return "Car [age=" + age + "]";
}
}
YellowCar is build without passing the Environment variable to the constructor, but using the #Value annotation:
package com.example.helper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
#Component
public class YellowCar {
#Value("${car.age}")
private int age;
#Override
public String toString() {
return "YellowCar [age=" + age + "]";
}
}
This is the program output:
Car [age=15]
YellowCar [age=0]
As you can see, age of YellowCar was not properly injected (it equals 0).
My goal: I'd like not to pass everywhere Environment object to the constructor of other classes... I'd like to use #Value annotatnio instead. Could somebody explain me:
1) why my code is not working?
2) how this code should be updated in order to get the following output?
Car [age=15]
YellowCar [age=15]
Thanks!
This happens, because you instantiate YellowCar directly. In order to make thing work, #Autowire YellowCar inside HelperApplication and use this injected instance like this(not tested):
#Autowired
private YellowCar yellowCar;
public static void main(String[] args) {
SpringApplication.run(HelperApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println (new RedCar(env));
System.out.println (yellowCar);
}
Explanation:
When you creating class using new, Spring knows nothing about this new instance, hence, it cannot inject anything. But when instance is created through Spring infrastructure (I'm trying not use a lot of slang words here), it will have all fields injected: when you mark class with #Component annotation or create method with #Bean annotation, you tell Spring, that you want it to be a Bean. On application startup, spring creates instances of this beans - by default only one instance per context - and inject this instance into all other beans, where requested. In this case, this instance is being processed by spring infrastructure (exact class which do it - AutowiredAnnotationBeanPostProcessor), and instances of other beans will be injected into our bean.
UPD: You can do the same thing with RedCar:
#Autowired
private YellowCar yellowCar;
#Autowired
private RedCar redCar;
public static void main(String[] args) {
SpringApplication.run(HelperApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println (redCar);
System.out.println (yellowCar);
}

Spring Boot app requires a bean annotated with #Primary to start

I'm seeing the following message on a Spring Boot app startup:
> *************************** APPLICATION FAILED TO START
> ***************************
>
> Description:
>
> Field oauthProps in com.example.authservice.AuthorizationServerConfig
> required a single bean, but 2 were found:
> - OAuthProperties: defined in file [/Users/simeonleyzerzon/abc/spring-security/spring-security-5-oauth-client/auth-service/target/classes/com/example/authservice/config/OAuthProperties.class]
> - kai-com.example.authservice.config.OAuthProperties: defined in null
>
>
> Action:
>
> Consider marking one of the beans as #Primary, updating the consumer
> to accept multiple beans, or using #Qualifier to identify the bean
> that should be consumed
I'm wondering what's causing the duplication of that bean and how one can remove it without the necessity of using the #Primary annotation? Not sure where the kai-com package(?) from the above is coming from.
Here's the bean in question:
package com.example.authservice.config;
//#Primary
#Component
#ConfigurationProperties(prefix="kai")
#Setter #Getter
public class OAuthProperties {
private String[] redirectUris;
private String clientId;
private String clientSecret;
private final Token token = new Token();
#Setter #Getter
public static class Token{
private String value;
private String type="";
}
}
and the app/config, etc.:
package com.example.authservice;
import ...
#SpringBootApplication
public class AuthServiceApplication {
public static void main(String[] args) {
SpringApplication.run(AuthServiceApplication.class, args);
}
}
#Controller
class MainController {
#GetMapping("/")
String index() {
return "index";
}
}
#RestController
class ProfileRestController {
#GetMapping("/resources/userinfo")
Map<String, String> profile(Principal principal) {
return Collections.singletonMap("name", principal.getName());
}
}
#Configuration
#EnableResourceServer
class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/resources/**")
.authorizeRequests()
.mvcMatchers("/resources/userinfo").access("#oauth2.hasScope('profile')");
}
}
#Configuration
#EnableAuthorizationServer
#EnableConfigurationProperties(OAuthProperties.class)
class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired private OAuthProperties oauthProps;
private final AuthenticationManager authenticationManager;
AuthorizationServerConfig(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient(oauthProps.getClientId())
.secret(oauthProps.getClientSecret())
.authorizedGrantTypes("authorization_code")
.scopes("profile")
.redirectUris(oauthProps.getRedirectUris());
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(this.authenticationManager);
if (oauthProps.getToken().getType().equals("jwt")) {
endpoints.tokenStore(this.tokenStore()).accessTokenConverter(jwtAccessTokenConverter());
}else {
endpoints.tokenEnhancer(eapiTokenEnhancer());
}
}
TokenEnhancer eapiTokenEnhancer() {
return new TokenEnhancer() {
#Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
DefaultOAuth2AccessToken result = new DefaultOAuth2AccessToken(accessToken);
result.setValue(oauthProps.getToken().getValue());
return result;
}
};
}
#Bean
JwtAccessTokenConverter jwtAccessTokenConverter() {
KeyStoreKeyFactory factory = new KeyStoreKeyFactory(new ClassPathResource(".keystore-oauth2-demo"), //keystore
"admin1234".toCharArray()); //storepass
JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
jwtAccessTokenConverter.setKeyPair(factory.getKeyPair("oauth2-demo-key")); //alias
return jwtAccessTokenConverter;
}
#Bean
TokenStore tokenStore() {
return new JwtTokenStore(this.jwtAccessTokenConverter());
}
}
#Service
class SimpleUserDetailsService implements UserDetailsService {
private final Map<String, UserDetails> users = new ConcurrentHashMap<>();
SimpleUserDetailsService() {
Arrays.asList("josh", "rob", "joe")
.forEach(username -> this.users.putIfAbsent(
username, new User(username, "pw", true, true, true, true, AuthorityUtils.createAuthorityList("USER","ACTUATOR"))));
}
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return this.users.get(username);
}
}
#Configuration
#EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
}
}
Eclipse too seems to be only aware of a single instance of the bean:
When using #EnableConfigurationProperties with #ConfigurationProperties you will get a bean named <prefix>-<fqn>, the kai-com.example.authservice.config.OAuthProperties. (See also the reference guide).
When the #ConfigurationProperties bean is registered that way, the bean has a conventional name: <prefix>-<fqn>, where <prefix> is the environment key prefix specified in the #ConfigurationProperties annotation and <fqn> is the fully qualified name of the bean. If the annotation does not provide any prefix, only the fully qualified name of the bean is used.
The bean name in the example above is acme-com.example.AcmeProperties. (From the Reference Guide).
The #Component will lead to another registration of the bean with the regular name of the classname with a lowercase character. The other instance of your properties.
the #EnableConfigurationProperties annotation is also automatically applied to your project so that any existing bean annotated with #ConfigurationProperties is configured from the Environment. You could shortcut MyConfiguration by making sure AcmeProperties is already a bean, as shown in the following example: (From the Reference Guide).
The key here is that #EnableConfigurationProperties is already globally applied and processes any bean annotated with #ConfigurationProperties.
So basically you where mixing the 2 ways of using #ConfigurationProperties and Spring Boot 2 now prevents that misuse. This way you write better code (and reduce the memory footprint and performance slightly).
So either remove the #Component or remove the #EnableConfigurationProperties, either way will work.
The following change (removing of #EnableConfigurationProperties) seems to help relieving the need for the #Primary annotation:
#Configuration
#EnableAuthorizationServer
//#EnableConfigurationProperties(OAuthProperties.class)
class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired private OAuthProperties oauthProps;
Perhaps someone can describe the internal Spring mechanics of secondary bean creation (and its namespace/package assignment) by that annotation which seemingly causes the collision with the #Autowired one, or point me to the appropriate documentation of this behavior.

How to inject property values into Spring Boot beans

In my spring boot application, i'am trying to inject variable's value from the config file application.properties to my java class and i'm getting a null value.
here is the configuration of my application.properties file:
myapp.username=user#user.com
myapp.password=user
here is where i call the configuration entries:
#Component
public class MyClass{
#Value("${myapp.username}")
public String username;
#Value("${myapp.password}")
public String password;
public static void main(String[] args) {
System.out.println(password);
}
}
I hope there someone how did deal with the same problem, thanks.
you can use this example add bean to your config like this :
#Configuration
#ComponentScan(basePackages = "youpackagebase")
#PropertySource(value = { "classpath:application.properties" })
public class AppConfig {
/*
* PropertySourcesPlaceHolderConfigurer Bean only required for #Value("{}") annotations.
* Remove this bean if you are not using #Value annotations for injecting properties.
*/
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
and in your bean :
#Component
public class NetClient {
#Value("${bigwater.api_config.url.login}")
public String url_login;
Best Regards
You are not even letting the Spring Boot container to boot (initialize) as you are are writing the code directly under main.
You should have an Application class as shown below to launch the Spring boot container properly, look here.
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
As far as my understanding you wanted to execute your code once the container is started, so follow the below steps:
Add the above Application class and then in your NetClient component class add a #Postconstruct method & this method will be called automatically once the bean is ready, refer the code below:
#Component
public class NetClient {
#Value("${bigwater.api_config.url.login}")
public String url_login;
#Value("${bigwater.api_config.url.ws}")
public static String url_ws;
#Value("${bigwater.api_config.username}")
public String username;
#Value("${bigwater.api_config.password}")
public String password;
#Postconstruct
public void init() {
//place all of your main(String[] args) method code here
}
//Add authentification() method here
}

Resources