I have the following yaml configuration in a Spring Boot application:
document-types:
de_DE:
REPORT: ["Test"]
This is loaded using the following class and works perfectly fine when the SpringBootApplication is started (you can debug the DemoApplication.java to verify):
#Component
#ConfigurationProperties
#Data
public class DocumentTypeConfiguration {
private Map<String, Map<String, List<String>>> documentTypes;
}
But when I execute the following test, the documentTypes aren't loaded (it's null even though the someSrting value is properly set)
#SpringBootTest(classes = {DocumentTypeConfiguration.class, DocumentTypeService.class})
class DocumentTypeServiceTest {
#Autowired
private DocumentTypeConfiguration documentTypeConfiguration;
#Value("${test}")
private String someSrting;
#Autowired
private DocumentTypeService documentTypeService;
#Test
void testFindDocumentType() {
String documentType = "Test";
String result = documentTypeService.getDocumentType(documentType);
String expected = "this";
assertEquals(expected, result);
}
}
Any idea what I might be doing wrong? Or maybe SpringBootTest doesn't support complex types for properties?
Source code and a test can be find here: https://github.com/nadworny/spring-boot-test-properties
This annotation was missing in the test: #EnableConfigurationProperties
So the test class looks like this:
#SpringBootTest(classes = {DocumentTypeConfiguration.class, DocumentTypeService.class})
#EnableConfigurationProperties(DocumentTypeConfiguration.class)
class DocumentTypeServiceTest {
#Autowired
private DocumentTypeConfiguration documentTypeConfiguration;
#Value("${test}")
private String someSrting;
#Autowired
private DocumentTypeService documentTypeService;
#Test
void testFindDocumentType() {
String documentType = "Test";
String result = documentTypeService.getDocumentType(documentType);
String expected = "this";
assertEquals(expected, result);
}
}
Related
I'm working on spring boot project. All things work perfectly but while unit testing saveBooking() method of controller then unit testing become failure. In Failure Trace I get java.lang.AssertionError: Response content expected:<Saved> but was:<SAVED>. This code worke perfectly in my postman but failure in unit testing.
Here down is my code:
Model
public class Booking {
private String bookingId;
private String passangerName;
private String flightName;
private String source;
private String destination;
// constructor, getter and setter
}
Controller
#RestController
public class BookingController {
#Autowired
private BookingService bookingService;
#PostMapping("/booking")
public String saveBooking(#RequestBody Booking booking) {
boolean saved = bookingService.saveBooking(booking);
return "SAVED";
}
}
TestController
#WebMvcTest(controllers = BookingController.class)
public class BookingControllerTest {
#MockBean
private BookingService bookingService;
#Autowired
private MockMvc mockMvc;
#Test
public void testSaveBooking() throws Exception
{
Mockito.when(bookingService.saveBooking(any())).thenReturn(true);
String bookingDetails = "{\r\n"
+ " \"bookingId\": \"AA0456\",\r\n"
+ " \"passangerName\": \"Michael\",\r\n"
+ " \"flightName\": \"Air American\",\r\n"
+ " \"source\": \"California\",\r\n"
+ " \"destination\": \"Dubai\"\r\n"
+ "}";
RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/booking").contentType(MediaType.APPLICATION_JSON).content(bookingDetails);
mockMvc.perform(requestBuilder).andDo(print()).andExpect(status().isOk()).andExpect(content().string("Saved"));
}
}
SAVED != Saved
return "SAVED";
but expect
andExpect(content().string("Saved"));
Solution 1:
Try to use an enum so you can't misspell it
Solution 2:
check the string with .toLowerCase() when you check, so the case doesn't matter.
Solution 3:
Use
return "SAVED";
and
andExpect(content().string("SAVED"));
so the strings match.
I'm following the 24.8.3 Merging Complex Types section of Spring Boot's 24. Externalized Configuration documentation.
I have this config.yaml file:
acme:
list:
- name: my name
description: my description
- name: another name
description: another description
The Properties file looks like this:
#ConfigurationProperties("acme")
#YamlPropertySource(value = { "classpath:/config.yaml" })
public class AcmeProperties {
private final List<MyPojo> list = new ArrayList<>();
public List<MyPojo> getList() {
return this.list;
}
}
The MyPojo class:
public class MyPojo {
private String name;
private String description;
public MyPojo(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
The test, which fails, looks like this:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = { AcmeProperties.class })
public class AcmePropertiesTest {
#Autowired
private AcmeProperties properties;
#Test
public void getOpScoringClusters() {
Assert.assertEquals(2, properties.getList().size()); // FAIL!
}
}
Spring Boot version 1.5.6.
Basically I want to have a list of typed properties. What am I doing wrong?
Several comments have highlighted multiple issues with the code presented.
Firstly, the fields inside a configuration properties can't be final as spring uses the setter to set the value.
Secondly, #YamlPropertySource is not something provided by spring so won't do anything in this context.
Thirdly, even if you did use the spring PropertySource annotation, unfortunately you can't use it with yaml files.
YAML files cannot be loaded by using the #PropertySource annotation.
I've created a sample project that uses the code you presented and has been modified so that it passes the unit test. It's using spring boot 2.x instead of 1.x but the only significant difference should be the annotations used in the test class.
https://github.com/michaelmcfadyen/spring-boot-config-props-demo
I am having Spring Boot application and having application.yml with different properties and loading as below.
#Configuration
#ConfigurationProperties(prefix="applicationprops")
public class ApplicationPropHolder {
private Map<String,String> mapProperty;
private List<String> myListProperty;
//Getters & Setters
}
My Service or Controller Class in which I get this properties like below.
#Service
public ApplicationServiceImpl {
#Autowired
private ApplicationPropHolder applicationPropHolder;
public String getExtServiceInfo(){
Map<String,String> mapProperty = applicationPropHolder.getMapProperty();
String userName = mapProperty.get("user.name");
List<String> listProp = applicationPropHolder.getMyListProperty();
}
}
My application.yml
spring:
profile: dev
applicationprops:
mapProperty:
user.name: devUser
myListProperty:
- DevTestData
---
spring:
profile: stagging
applicationprops:
mapProperty:
user.name: stageUser
myListProperty:
- StageTestData
My questions are
In my Service class i am defining a variable and assigning Propertymap for every method invocation.Is it right appoach?
Is there any other better way I can get these maps without assigning local variable.
There are three easy ways you can assign the values to instance variables in your bean class.
Use the #Value annotation as follows
#Value("${applicationprops.mapProperty.user\.name}")
private String userName;
Use the #PostConstruct annotation as follows
#PostConstruct
public void fetchPropertiesAndAssignToInstanceVariables() {
Map<String, String> mapProperties = applicationPropHolder.getMapProperty();
this.userName = mapProperties.get( "user.name" );
}
Use #Autowired on a setter as follows
#Autowired
public void setApplicationPropHolder(ApplicationPropHolder propHolder) {
this.userName = propHolder.getMapProperty().get( "user.name" );
}
There may be others, but I'd say these are the most common ways.
Hope, you are code is fine.
Just use the below
#Configuration
#ConfigurationProperties(prefix="applicationprops")
public class ApplicationPropHolder {
private Map<String,String> mapProperty;
private List<String> myListProperty;
public String getUserName(){
return mapProperty.get("user.name");
}
public String getUserName(final String key){
return mapProperty.get(key);
}
}
#Service
public ApplicationServiceImpl {
#Autowired
private ApplicationPropHolder applicationPropHolder;
public String getExtServiceInfo(){
final String userName = applicationPropHolder.getUserName();
final List<String> listProp = applicationPropHolder.getMyListProperty();
}
}
I can't get Spring Data Rest with class inheritance working.
I'd like to have a single JSON Endpoint which handles all my concrete classes.
Repo:
public interface AbstractFooRepo extends KeyValueRepository<AbstractFoo, String> {}
Abstract class:
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
#JsonSubTypes({
#JsonSubTypes.Type(value = MyFoo.class, name = "MY_FOO")
})
public abstract class AbstractFoo {
#Id public String id;
public String type;
}
Concrete class:
public class MyFoo extends AbstractFoo { }
Now when calling POST /abstractFoos with {"type":"MY_FOO"}, it tells me: java.lang.IllegalArgumentException: PersistentEntity must not be null!.
This seems to happen, because Spring doesn't know about MyFoo.
Is there some way to tell Spring Data REST about MyFoo without creating a Repository and a REST Endpoint for it?
(I'm using Spring Boot 1.5.1 and Spring Data REST 2.6.0)
EDIT:
Application.java:
#SpringBootApplication
#EnableMapRepositories
public class Application {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
I'm using Spring Boot 1.5.1 and Spring Data Release Ingalls.
KeyValueRepository doesn't work with inheritance. It uses the class name of every saved object to find the corresponding key-value-store. E.g. save(new Foo()) will place the saved object within the Foo collection. And abstractFoosRepo.findAll() will look within the AbstractFoo collection and won't find any Foo object.
Here's the working code using MongoRepository:
Application.java
Default Spring Boot Application Starter.
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
AbstractFoo.java
I've tested include = JsonTypeInfo.As.EXISTING_PROPERTY and include = JsonTypeInfo.As.PROPERTY. Both seem to work fine!
It's even possible to register the Jackson SubTypes with a custom JacksonModule.
IMPORTANT: #RestResource(path="abstractFoos") is highly recommended. Else the _links.self links will point to /foos and /bars instead of /abstractFoos.
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type")
#JsonSubTypes({
#JsonSubTypes.Type(value = Foo.class, name = "MY_FOO"),
#JsonSubTypes.Type(value = Bar.class, name = "MY_Bar")
})
#Document(collection="foo_collection")
#RestResource(path="abstractFoos")
public abstract class AbstractFoo {
#Id public String id;
public abstract String getType();
}
AbstractFooRepo.java
Nothing special here
public interface AbstractFooRepo extends MongoRepository<AbstractFoo, String> { }
Foo.java & Bar.java
#Persistent
public class Foo extends AbstractFoo {
#Override
public String getType() {
return "MY_FOO";
}
}
#Persistent
public class Bar extends AbstractFoo {
#Override
public String getType() {
return "MY_BAR";
}
}
FooRelProvider.java
Without this part, the output of the objects would be separated in two arrays under _embedded.foos and _embedded.bars.
The supports method ensures that for all classes which extend AbstractFoo, the objects will be placed within _embedded.abstractFoos.
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class FooRelProvider extends EvoInflectorRelProvider {
#Override
public String getCollectionResourceRelFor(final Class<?> type) {
return super.getCollectionResourceRelFor(AbstractFoo.class);
}
#Override
public String getItemResourceRelFor(final Class<?> type) {
return super.getItemResourceRelFor(AbstractFoo.class);
}
#Override
public boolean supports(final Class<?> delimiter) {
return AbstractFoo.class.isAssignableFrom(delimiter);
}
}
EDIT
Added #Persistent to Foo.java and Bar.java. (Adding it to AbstractFoo.java doesn't work). Without this annotation I got NullPointerExceptions when trying to use JSR 303 Validation Annotations within inherited classes.
Example code to reproduce the error:
public class A {
#Id public String id;
#Valid public B b;
// #JsonTypeInfo + #JsonSubTypes
public static abstract class B {
#NotNull public String s;
}
// #Persistent <- Needed!
public static class B1 extends B { }
}
Please see the discussion in this resolved jira task for details of what is currently supported in spring-data-rest regarding JsonTypeInfo. And this jira task on what is still missing.
To summarize - only #JsonTypeInfo with include=JsonTypeInfo.As.EXISTING_PROPERTY is working for serialization and deserialization currently.
Also, you need spring-data-rest 2.5.3 (Hopper SR3) or later to get this limited support.
Please see my sample application - https://github.com/mduesterhoeft/spring-data-rest-entity-inheritance/tree/fixed-hopper-sr3-snapshot
With include=JsonTypeInfo.As.EXISTING_PROPERTY the type information is extracted from a regular property. An example helps getting the point of this way of adding type information:
The abstract class:
#Entity #Inheritance(strategy= SINGLE_TABLE)
#JsonTypeInfo(use=JsonTypeInfo.Id.NAME,
include=JsonTypeInfo.As.EXISTING_PROPERTY,
property="type")
#JsonSubTypes({
#Type(name="DECIMAL", value=DecimalValue.class),
#Type(name="STRING", value=StringValue.class)})
public abstract class Value {
#Id #GeneratedValue(strategy = IDENTITY)
#Getter
private Long id;
public abstract String getType();
}
And the subclass:
#Entity #DiscriminatorValue("D")
#Getter #Setter
public class DecimalValue extends Value {
#Column(name = "DECIMAL_VALUE")
private BigDecimal value;
public String getType() {
return "DECIMAL";
}
}
I have a spring boot application which is using a spring cloud config.
How can i map a configuration element with some java object.
My config is something like this:
clients:
- id : 1
name: client 1
groups : [a,b]
- id : 2
name: client 2
groups : [a]
And my java object is:
public class ClientInfo {
private String clientId;
private List<String> profiles;
public ClientInfo(String clientId, List<String> pips) {
this.clientId = clientId;
this.profiles = pips;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public List<String> getProfiles() {
return profiles;
}
public void setProfiles(List<String> profiles) {
this.profiles = profiles;
}
}
I want to map my configuration with List
Use below code to configure configuration properties in to java Object,
#Component
#EnableConfigurationProperties
#ConfigurationProperties(prefix = "clients")
public class ClientInfo {
private String id;
private String name;
private List<String> groups;
public String getId(){ return id;}
public String getName(){ return name;}
public List<String> getGroups(){ return groups;}
}
Check following for example http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
Inject this class in another class :
#Autowired
private ClientInfo clientInfo;
The above auto wiring will not work if the class is instantiated using "new operator".
Actually I found the reason why it was not working.
All that was needed is to have another class which contains a list of ClientInfo and have #EnableConfigurationProperties and #ConfigurationProperties annotations on it. This is because "clients" in my configuration is a list. After this change we can use #Autowired annotation to inject the configuration.