How to load application.properties in spring framework? - java

My spring application start's via WebApplicationInitializer.
public class WebAppInitializer implements WebApplicationInitializer
{
#Override
public void onStartup(ServletContext servletContext) throws ServletException
{
....
}
}
I have Config class
#Configuration
#PropertySources({
#PropertySource(value = "classpath:application.properties"))
})
public class MainConfig
{
....
}
And in application.properties file I try to override the spring and logging properties
logging.level.com.app=DEBUG
logging.level.org.springframework.web=DEBUG
The file application.properties is in the directory src/main/resources
But it has no effect - means that no property is applied to the spring or logging system

Try using SpringBoot. In spring boot application.properties is read by default and you don't even need to use #PropertySource to read it. You can download a spring boot application skeleton from https://start.spring.io/

Related

Config resource handlers for Spring Boot

How to do the same that I pointed using Spring Boot (+Security)? Implementation of WebMvcConfigurer interface resets a lots settings, which were performed by Spring BOOT did automatically. For example, setting in application.properties "spring.mvc.hiddenmethod.filter.enabled=true" stopped to work. Question in that how to setting a binding of multiple ResourceHandler:ResourceLocation pairs without configuring the extra.
I don't know how to make things right.
#Configuration
#EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**")
.addResourceLocations("classpath:/static/assets/css/");
registry.addResourceHandler("/images/**")
.addResourceLocations("classpath:/static/assets/images/");
registry.addResourceHandler("/js/**")
.addResourceLocations("classpath:/static/assets/js/");
registry.addResourceHandler("/person-storage/**")
.addResourceLocations("classpath:/storage/person-images/");
}
}
I tried to use settings in application.properties for spring boot. I tried to create #Bean of "addResourceHandler" to I won't implement interface WebMvcConfigurer fully.

Spring load properties file programmatically

This is how I load application.properties if the file is on the classpath.
#ComponentScan
#Configuration
#PropertySource("classpath:application.properties")
public class MyApplication {
// Have some public methods
}
public class Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyApplication.class);
MyApplication app = context.getBean(MyApplication.class);
// execute methods in app
}
}
We are trying to deploy the application where the properties file is stored externally on a Google Cloud bucket (GCS). I can load the properties file from GCS and save it in memory. How do I pass the properties to the Application context and override the properties loaded from the classpath?
If it matters, it's a standalone app, not Spring Boot.
If you have it in memory then it should not be a problem. Get rid of #PropertySource("classpath:application.properties") annotation and register PropertySourcesPlaceholderConfigurer bean manually.
#Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
properties.setLocation([any implementation of Resource interface - use most applicable out of available or implement it by yourself]);
return properties;
}
You can read external properties file following way.
#PropertySources({
#PropertySource("classpath:application.properties"),
#PropertySource(value = "${external.properties}", ignoreResourceNotFound = true)
})
When you run the jar file, pass external.properties filepath following way
java -Dexternal.properties=file:/path_to_properties my-service.jar

How to load Application.properties file dynamically based on Profile in Spring MVC?

Hi I am learning Spring MVC and I want to know How to load application.properties file dynamically.
I am adding HibernateConfig.java file and AppConfig.java file. I want to load application properties file dynamically using profiles. For Example: dev, test, prod. I have tried to use dynamic name application-{profile}.properties and also tried profile annotation. but not able to understand how they are actually working. I have created a different application.properties files.
application-dev
application-test
application-prod
This property file contains my DB related data. but I don't know how to set profile and how to load PropertySource based on a profile.
I have set the active profile in my appConfig file. Please help me in understanding how to configure profile and application.properties using spring MVC Java-based configuration. I have searched and found many solutions for XML based configuration but I haven't found any proper answer for java based configuration.
HibernateConfig.java
#Configuration
#EnableTransactionManagement
#ComponentScan({"com.project.configuration"})
#PropertySource(value = {"classpath:application.properties"})
public class HibernateConfiguration {
#Autowired
private Environment env;
#Bean
public LocalSessionFactoryBean sessionFactory(){
return sessionFactory;
}
#Bean
public DataSource dataSource(){
/* loading DB */
return dataSource;
}
#Bean
public Properties hibernateProperties(){
}
}
AppConfig.java
#Override
public void onStartup(ServletContext servletContext) throws ServletException
{
super.onStartup(servletContext);
servletContext.setInitParameter("spring.profiles.active", "dev");
}
I think you cant set this parameter at that time, its already too late. You have to start the app with specified profile (or set it in bootstrap file) . You can pass it as an argument or place it in:
application.properities
Under key: spring.profiles.active
When you set this to 'dev' it will read main application.properities and then the profile one. More about how to set it:
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

Spring Yml configuration for CORS not used

I have configured the allowed origins for CORS in the Spring yml configuration as follows.
endpoints:
cors:
allowed-origins: http://client.local
allow-credentials: true
But it wasn't applied until I added a Java configuration as follows
#Configuration
#EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {
#Value("${endpoints.cors.allowed-origins}")
private String allowedOrigins;
#Value("${endpoints.cors.allow-credentials}")
private boolean allowCredentials;
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins(allowedOrigins)
.allowCredentials(allowCredentials);
}
}
I want to keep the yml configuration and discard the Java configuration, why is the yml config not applied?
I know, it might be too late, but I'll try...
Have you added spring-boot-starter-actuator to your dependencies?
Instead of using custom properties use endpoints provided by Spring Boot.
Ex:
management.endpoints.web.cors.allowed-origins=http://domain:port
Spring Boot Application.properties configuration

Spring - Share UserDetailsService across WebMVC & Security

I'm implementing a web application with some basic login mechanism using Spring & Spring Security. All fine, but I'm facing a question (maybe it's not a problem, let's see).
My WebApp is structured like this (No XML Config, Servlet-3.0 and Spring 4.0):
WebAppInitializer
Intention: Configure WebApplication
public class WebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(AppConfig.class);
applicationContext.refresh();
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(Dispatcher);
context.setParent(applicationContext);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher-servlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
}
}
SecurityWebApplicationInitializer.java
Intention: Add Security
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
public SecurityWebApplicationInitializer() {
super(SecurityConfig.class);
}
}
There are also classes:
AppConfig (#Configuration, #ComponentScan for xyz.services)
DispatcherConfig (#Configuration, #EnableWebMVc and #ComponentScan for xyz.controller)
SecurityConfig (#Configuration, #EnableWebSecurity, #ComponentScan for xyz.services)
CustomerUserDetailsService implementing UserDetailsService (#Service)
My problem/question:
I want to use the * CustomerUserDetailsService* in Security for the AuthenticationManagerBuilder and in my controllers - is there a way to have only one instance of the UserDetailsService? In this configuration it will create two instances: one for the Application Context and one for the Security Context. Did I miss anything in the configuration? Or is this the favourite way to have it configured?
Another question beside that is: is there any way to use this configuration supporting #Secured annotation on my controller? There was no way to get this working.

Categories

Resources