#CreatedBy becomes null when updating - spring-boot

I have this entity:
#Entity
#EntityListeners( AuditingEntityListener.class )
public class Employee {
#Id
#GeneratedValue
int id;
private String name;
...
#LastModifiedBy
private String modifiedBy;
#CreatedBy
private String createdBy;
}
And i have this config class:
#Configuration
#EnableJpaAuditing
public class DataConfig {
#Bean
public AuditorAware<String> auditorAware() {
return () ->
SecurityContextHolder.getContext().getAuthentication().getName();
}
}
The problem is:
When updating entity, the created_by becomes null.
Any help please.

I'd suggest to you to ensure if your spring boot app is scanning the DataConfig class.
In addition, well in case of having a REST Service (I don't know because that info is not added to the question) but bear in mind a REST Service is Stateless, and you need fetch the Authorization from the request to add it to the spring security context BEFORE executing the request.
But if your spring boot app is just a Spring MVC one with basic Authorization, be sure you have an open session once the data is updated/created

Related

Spring Boot #ConfigurationProperties, skip #Configuration if not valid

In a Spring Boot 1.5.13 project, I have a #Configuration object with some #NotEmpty fields:
#Configuration
#Validated
public class Test {
#NotEmpty
private String name;
private String optionalOne;
private String optionalTwo;
#NotEmpty
private String location;
...
}
And a #ConfigurationProperties class that loads it from application.yml:
#ConfigurationProperties(prefix="test.config")
public class TestConfig {
#Valid
Map<String, Test> testRecords = new HashMap<>();
...
}
There are several "Test" records in the configuration files.
Default behavior from spring is that if validation fails, like if one of the records has a missing location, then an error prevents the app from starting up.
I would instead like the behavior to be that the invalid record is logged and skipped, so that the app continues startup, loading only the valid records, and loading no records that are missing the #NotEmpty fields.
How can I accomplish this?
I would suggest you to implement the validation yourself without any annotations. After the beans are constructed check the constraints programatically (maybe in a #PostConstruct method) to avoid fighting with Spring.

javax validation api not working for pojo validation

I have a POJO class where the class variables are getting injected by #Value annotation. I am trying to validate my class variables using javax validation api & so I have tried #NotNull, #NotEmpty and #NotBlank, but all of them seem not to be validating or throwing any kind of exception even when a blank/null value is present in the application.yml file. Any idea as to how can I validate my POJO here using the javax validation api?
PS: I am using lombok to generate my getter/setter.
Below is my sample code!
POJO Class:
#Component
#Getter
#Setter
public class Credentials {
#NotBlank
#Value("${app.username}")
private String user_name;
#NotBlank
#Value("${app.password}")
private String password;
}
Below is the application.yml file:
app:
username: '#{null}'
password: passWord
Even if I provide a blank value, I don't get any exception when I try to print these values in the console.
I think this can be applied.
#Data
#RequiredArgsConstructor
public class Credentials {
private final String user_name;
private final String password;
}
#Configuration
#Validated
public class CredentialsConfiguration {
#Bean
public Credentials credentials(
#NotBlank #Value("${app.username}") final String user_name,
#NotBlank #Value("${app.password}") final String password) {
return new Credentials(user_name, password);
}
}
Validation will only work for #ConfigurationProperties annotated classes combined with using #EnableConfigurationProperties.
The reason you don't get any exception is that #Value only looks for presence of the attribute in the properties, it doesn't care what the value of that attribute is, unless you are assigning a mis-matching datatype value.

I can do PUT but not POST with Spring Data Rest?

I have two simple entity like this:
public class Agent extends BasedEntity {
private String firstname;
private String lastname;
#ManyToOne
#JoinColumn(name="agency_id", nullable=true)
Agency agency;
}
and
public class Agency extends BasedEntity {
private String name;
private String address;
#OneToMany(mappedBy="agency")
private Set<Agent> agents;
}
#RepositoryRestResource
public interface AgencyRespository extends JpaRepository<Agency, Long> {
}
#RepositoryRestResource
public interface AgentsRespository extends JpaRepository<Agent, Long> {
}
When I do a PUT with
https://localhost:8080/api/v1/agents/64/agency
body:https://localhost:8080/api/v1/agencies/50
it goes through but if I do a POST to
https://localhost:8080/api/v1/agents/64/agency
body:https://localhost:8080/api/v1/agencies/50
I get a
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
You are using an old version of Spring Data Rest. POST is allowed from 2.3.x.
The latest version is 3.2.x. You should definetely ugrade to a newer version...
----------- Edit
I've just realized that the exception is NOT the inner HttpRequestMethodNotSupportedException from the RepositoryPropertyReferenceController class, but the 'default' org.springframework.web.HttpRequestMethodNotSupportedException.
This exception is never raised directly from the SRD package.
Maybe you have a filter which deny POST request or some kind of security settings.

SpringCloud-Bus does not refresh using webhook client

SpringCloud uses spring-cloud-config-monitor to automatically refresh the configuration of the message bus. It uses the webhook of github. After each update configuration is completed, the result of the request is:
github webhook response,However, the configuration is only updated in config-server, and config-client is not updated, and the config class used is annotated with #RefreshScope. What is the reason?
BeanClass:
#Data
#ConfigurationProperties(prefix = "book")
#Component
#RefreshScope
public class BookConfig implements Serializable {
private Integer max;
private Integer min;
private String author;
private List<String> bookList;
}

Spring Boot Use Custom Properties Service

I am working on a legacy project that has its own PropertyService class that manages the reloadable properties and so on.
The thing works pretty much OK, but the problem is now I have this property service, for my project, and an application.yml for the spring boot related properties.
The question is: is there a way to tell spring boot to load properties from something like a properties provider - a custom class or an adapter of sort ?
In this way I could manage my properties only through the existing module
Thank you for your help !
Try #ConfigurationProperties to customize the properties loading (see the example)
The code example
#Configuration
#ConfigurationProperties(locations = "classpath:mail.properties", prefix = "mail")
public class MailConfiguration {
public static class Smtp {
private boolean auth;
private boolean starttlsEnable;
// ... getters and setters
}
#NotBlank
private String host;
private int port;
private String from;
private String username;
private String password;
#NotNull
private Smtp smtp;
// ... getters and setters
#Bean
public JavaMailSender javaMailSender() {
// omitted for readability
}
}
So you define a bean which in fact returns properties

Resources