ConfigurationProperties for final fields doesn't work - java

I need to set data from application.yml file to my config class but when I trying to do it I get an error:
TestConfig is annotated with #ConstructorBinding but it is defined as a regular bean which caused dependency injection to fail.
My application.yml file looks like the following:
test:
app:
id: app_id
My TestConfig class looks like this:
#Configuration
#ConfigurationProperties(prefix = "test.app")
#ConstructorBinding
public class TestConfig {
private final String id;
public TestConfig(String id) {
this.id = id;
}
}
I'm trying to do like this but it doesn't work for me.
Where I was wrong?

According to :
https://www.baeldung.com/configuration-properties-in-spring-boot#immutable-configurationproperties-binding
You will need to remove the #Configuration from your TestConfig.class.
Furthermore, it's important to emphasize that to use the constructor binding, we need to explicitly enable our configuration class either with #EnableConfigurationProperties or with #ConfigurationPropertiesScan.
--------- Edited -----
#ConfigurationProperties(prefix = "test.app")
#ConstructorBinding
public class TestConfig {
private final int id;
public TestConfig (int id)
this.id = id
}
public String getId() {
return id;
}
}
#SpringBootApplication
#ConfigurationPropertiesScan
public class YourApp{
public static void main(String[] args) {
SpringApplication.run(YourApp.class, args);
}
}

Related

#ConfigurationProperties does not work when using classes in the #SpringBootTest

application.yml
foo:
name: hun
FooConfigurationProperty
foo.name in application.yml is bound.
#Getter
#Setter
#Component
#ConfigurationProperties("foo")
public class FooConfigurationProperty {
private String name;
}
For quick testing, the FooConfigurationProperty bean was added using the classes property.
FooTest
#SpringBootTest(classes = FooConfigurationProperty.class)
public class FooTest {
#Autowired
FooConfigurationProperty fooConfigurationProperty;
#Test
public void fooTest() {
System.out.println(fooConfigurationProperty.getName());
}
}
The above results are output null rather than hun.
Why is null output when classes have specified to use a specific bean?

NoUniqueBeanDefinitionException: No qualifying bean of type 'AppProperties' available: expected single matching bean but found 3

I am trying to load the api key value from the application.properties file and below are the class files. I am unable to start the application as it is not able to find the unique bean. Not sure what i am missing. Can someone please help.
This is our AppProperties.java
#Component
#PropertySource("classpath:application.properties")
#ConfigurationProperties(prefix = AppProperties.APP_PROPERTIES_PREFIX)
public class AppProperties {
public static final String APP_PROPERTIES_PREFIX = "bi";
private String accessTokenUri;
private String clientId;
private String clientSecret;
private String basicAuth;
private String apiKey;
//getters and setters
}
This is our DiagnosticProperties.java
#Component
#PropertySource("classpath:application.properties")
#ConfigurationProperties(prefix = "bi")
public class DiagnosticProperties extends AppProperties {
private String diagnosisUrl;
//getters and setters
}
This is our ObservationProperties.java
#Component
#PropertySource("classpath:application.properties")
#ConfigurationProperties(prefix = "bi")
public class ObservationProperties extends AppProperties {
private String observationUrl;
//getters and setters
}
This is our DiagnosticServiceImpl.java
#Service
public class DiagnosticServiceImpl implements DiagnosticService {
private static final Logger LOGGER =
LoggerFactory.getLogger(ObservationServiceImpl.class);
private final WebClient webClient;
private final DiagnosticProperties diagnosticProperties;
public DiagnosticServiceImpl(final WebClient webClient,final DiagnosticProperties
diagnosticProperties) {
this.webClient = webClient;
this.diagnosticProperties = diagnosticProperties;
}
#Override
public Mono<DiagnosticResponse> getPatientDiagnosticDetails(final String uri) {
return diagnosticDetails(uri);
}
You should not put any annotations on the AppProperties (that could have been an abstract class). The classes that inherit from it only need #ConfigurationProperties(prefix = "..") and #Component or they could be also enabled with #EnableConfigurationProperties from another configuration class.
When you inject - be specific about which configuration properties you want to inject - either by specifying a type - like you did in your example, or by adding #Qualifier("bean-name") to the parameter on the injection point.
Spring Boot out-of-the-box configures application.properties property source.

Spring Boot Autowiring From Another Module

I am trying to establish connection between 3 modules in my project. When I try to reach my object with #Autowired error shows up. I'll explain my scenario a little bit.
MODULES
All of these modules have been connected inside of pom.xml. Lets talk about my problem.
C -> ROUTE.JAVA
.
.
.
#Autowired
public CommuniticationRepository;
#Autowired
public Core core;
.
.
.
B -> CORE
public class Core {
private int id;
private String name;
private Date date;
public Core(int id, String name, Date date) {
this.id = id;
this.name = name;
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
ERROR
Field communicationRepositoryin com.demo.xyz.A.RestControllers.Route required
a bean of type 'com.demo.xyz.A.CommunicationRepository' that could not be
found.
Action:
Consider defining a bean of type 'com.demo.xyz.A.CommunicationRepository' in
your configuration.
A - > REPOSITORY.JAVA
#Component
#Repository
public interface CommunicationRepository extends CrudRepository<Communication, Date> {
List<Communication> findByDate(Date date);
void countByDate(Date date);
}
You should remove #Component and #Repository from CommunicationRepository if it is a spring data JPA repository.
You should define configurations in modules A and B.
#Configuration
#EnableJpaRepositories(basePackages ={"com.demo.xyz.A"})
#EntityScan(basePackages = {"com.demo.xyz.A"})
#ComponentScan(basePackages = {"com.demo.xyz.A"})
public class ConfigA {
}
// If you have no spring managed beans in B this is not needed
// If Core should be a spring managed bean, add #Component on top of it
#Configuration
#ComponentScan(basePackages = {"com.demo.xyz.B"})
public class ConfigB {
}
Then, in C, where you bootstrap the application, you should import the configurations for module A and module B. At this point, any beans from A and B will be available for autowiring in C.
#Configuration
#Import(value = {ConfigA.class, ConfigB.class})
public class ConfigC {
}
Basically if you want to use #Autowired annotation on top of any attribute and use it, Obviously there should be an initialized bean in the spring context to Autowire it to your usages. So here your problem is in your spring context, there is no such bean to autowire.
So the solution is you need to have those beans inside your spring context, there are multiple ways to get this done,
The classes that you need beans auto initialized inside the spring context as #Component
Ex :
#Component
public class Car{
or you can manually have a configuration file which returns such beans
Ex :
#Bean
public Car setCarBean(){
return new Car();
}
And this bean returning should be inside a #Configuration class.
please refer
Then if you are really sure that you have done with this, then correct #ComponentScan should work
EDIT
#SpringBootApplication
#ComponentScan(basePackages = { "com.demo.xyz.A", "com.demo.xyz.B"})
public class Application {
Try to add scanBasePackages in the Application class.
The default scan is for the package in which the Application class.
#SpringBootApplication(scanBasePackages = "com.demo.xyz")
public class Application {...}

Is it necessary to use #Configuration while working with spring annotations

I am working with a simple spring application to check #Configuration and #Bean(java based configuartion only),The program is working with both #Configuration and without it.So is it necessary to have it.
Here is my code,
Student.java
package com.cg.spring;
public class Student {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
}
Faculty.java
package com.cg.spring;
public class Faculty {
private int empId;
private String name;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Faculty [empId=" + empId + ", name=" + name + "]";
}
}
MyConfig.java
package com.cg.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class MyConfig {
#Bean
public Student stu()
{
return new Student();
}
#Bean
public Faculty fac()
{
return new Faculty();
}}
Client.java
package com.cg.spring;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Client {
public static void main(String[] args) {
ApplicationContext context=new
AnnotationConfigApplicationContext(MyConfig.class);
Student stu=(Student)context.getBean(Student.class);
Faculty fac=(Faculty)context.getBean(Faculty.class);
stu.setName("ajay");
stu.setId(101);
System.out.println(stu);
fac.setEmpId(202);
fac.setName("Kiran");
System.out.println(fac);
}}
The output is same with or without the #Configuration
Student [id=101, name=ajay]
Faculty [empId=202, name=Kiran]
Even tried with autowiring,it is also working without #Configuration
Student.java
package com.cg.spring;
import org.springframework.beans.factory.annotation.Autowired;
public class Student {
private int id;
private String name;
#Autowired
private Faculty faculty;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Faculty getFaculty() {
return faculty;
}
public void setFaculty(Faculty faculty) {
this.faculty = faculty;
}
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}}
Client.java
package com.cg.spring;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Client {
public static void main(String[] args) {
ApplicationContext context=new
AnnotationConfigApplicationContext(MyConfig.class);
Student stu=(Student)context.getBean(Student.class);
Faculty fac=(Faculty)context.getBean(Faculty.class);
stu.setName("ajay");
stu.setId(101);
System.out.println(stu);
fac.setEmpId(202);
fac.setName("Kiran");
System.out.println(fac);
stu.setFaculty(fac);
System.out.println(stu.getFaculty());
}}
When using Java based configuration with Spring you basically have 2 options (as you already noticed). You have the option to annotate a class with #Configuration and have all the #Bean annotated methods available as beans. However you can also do this without the #Configuration annotation. The latter is called the so called lite mode.
When using #Configuration classes the beans defined in there are regular Spring beans and when calling one method from another this will always result in the same instance of a bean. Spring detects the #Configuration classes and treats them in a very special way (it will create a proxy for those classes).
When using lite-mode the #Bean methods are basically nothing more than factory methods, although they participate in (part of) the lifecycle of Spring Beans. When calling them each call will get you a new bean. Which means that, inter bean dependencies, will get you new instances each time the method gets called.
Also I realised that if #Configuration is used defining dependencies as private is not permitted.
#Configuration
public class ProgrammingConfig {
// define bean for the fortune service
#Bean
private FortuneService javaFortuneService() {
return new JavaFortuneService();
};
// define bean for java coach and inject its dependencies
#Bean
public Coach javaCoach() {
return new JavaCoach(javaFortuneService());
}
}
will yield
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: #Bean method 'javaFortuneService' must not be private or final; change the method's modifiers to continue
Exception in thread "main" org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: #Bean method 'javaFortuneService' must not be private or final; change the method's modifiers to continue
whilst without the #Configuration annotation the program works even with a private dependency
#Configuration is required because it indicates that a class declares one or more #Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime. #Configuration annotation used for many other reasons. For example, #Configuration is meta-annotated with #Component, therefore #Configuration classes are candidates for component scanning (typically using Spring XML's <context:component-scan/> element) and therefore may also take advantage of #Autowired/#Inject like any regular #Component. More details references are available to the following Link -
Annotation Type Configuration
#Bean annotation on methods that are declared in classes not annotated with #Configuration is known as “lite” mode. In the “lite” mode, #Bean methods cannot declare inter-bean dependencies. Ideally, one #Bean method should not invoke another #Bean method in ‘lite’ mode.
Spring recommends that #Bean methods declared within #Configuration classes for full configuration. This kind of full mode can prevent many bugs.

NullPointerException on CrudRepository

I have created a repository but when I call my repository it gives a NullPointerException everytime. Can someone help me figure out why?
My repository
#Repository
public interface WorkflowObjectRepository extends CrudRepository<WorkflowObject, String> {
#Override
WorkflowObject findOne(String id);
#Override
void delete(WorkflowObject workflowObject);
#Override
void delete(String id);
#Override
WorkflowObject save(WorkflowObject workflowObject);
}
My Object
#Data
#Entity
#Table(name = "workflowobject")
public class WorkflowObject {
#GeneratedValue
#Column(name="id")
private String id;
#Column(name = "state_name")
private String stateName;
}
My test
public class Test {
#Autowired
static WorkflowObjectRepository subject;
public static void main(String[] args) {
final WorkflowObject obj = new WorkflowObject();
obj.setId("maha");
obj.setStateName("test");
subject.findOne("maha");
}
}
application.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/vtr?
autoReconnect=true
spring.datasource.username=vtr
spring.datasource.password=vtr
The problem is you are trying to autowire a static data member
#Autowired
static WorkflowObjectRepository subject;
What happens in your case is static is getting initialized before the bean so you are autowiring on null, just remove the static and deal with it as instance variable.
repositories are singletones so no point of making them static
In order to work properly with #Autowired you need to keep in mind that spring scans annotations to allow automatically classes load.
If you need to #Autowired some class, the class Test needs to have some annotation, that tells to Spring Boot to find it.
Your Test class need to have #Component, #Service, #Controller, #Repository, etc. Otherwise #Autowired will not work because Spring Boot not know your class and will not process it.
You can find some explanation here

Categories