();
84 | properties.put("hibernate.validator.apply_to_ddl", "false");
85 | properties.put("hibernate.validator.autoregister_listeners", "false");
86 | properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
87 | properties.put("hibernate.generate_statistics", env.getProperty("hibernate.generate_statistics"));
88 | // Second level cache configuration and so on.
89 | return properties;
90 | }
91 |
92 |
93 | }
--------------------------------------------------------------------------------
/src/main/java/com/javaetmoi/sample/config/MainConfig.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2014-2017 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 | package com.javaetmoi.sample.config;
15 |
16 | import jakarta.annotation.PostConstruct;
17 |
18 | import org.slf4j.Logger;
19 | import org.slf4j.LoggerFactory;
20 | import org.springframework.beans.factory.annotation.Autowired;
21 | import org.springframework.context.annotation.Configuration;
22 | import org.springframework.context.annotation.Import;
23 | import org.springframework.core.env.Environment;
24 |
25 | /**
26 | * Configuration of the business, persistence and security layers.
27 | */
28 | @Configuration
29 | @Import(value = {
30 | DataSourceConfig.class,
31 | InfrastructureConfig.class,
32 | RepositoryConfig.class,
33 | ServiceConfig.class,
34 | SecurityConfig.class
35 | } )
36 | public class MainConfig {
37 |
38 | private static final Logger LOG = LoggerFactory.getLogger(MainConfig.class);
39 |
40 | @Autowired
41 | private Environment env;
42 |
43 | /**
44 | * Application custom initialization code.
45 | *
46 | * Spring profiles can be configured with a system property
47 | * -Dspring.profiles.active=javaee
48 | *
49 | */
50 | @PostConstruct
51 | public void initApp() {
52 | LOG.debug("Looking for Spring profiles...");
53 | if (env.getActiveProfiles().length == 0) {
54 | LOG.info("No Spring profile configured, running with default configuration.");
55 | } else {
56 | for (String profile : env.getActiveProfiles()) {
57 | LOG.info("Detected Spring profile: {}", profile);
58 | }
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/com/javaetmoi/sample/config/RepositoryConfig.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2014-2017 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 | package com.javaetmoi.sample.config;
15 | import org.springframework.context.annotation.Configuration;
16 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
17 |
18 | /**
19 | * Enable and scan Spring Data repositories.
20 | *
21 | */
22 | @Configuration
23 | @EnableJpaRepositories("com.javaetmoi.sample.repository")
24 | public class RepositoryConfig {
25 | //
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/javaetmoi/sample/config/SecurityConfig.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2014-2017 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 | package com.javaetmoi.sample.config;
15 |
16 | import org.springframework.beans.factory.annotation.Autowired;
17 | import org.springframework.context.annotation.Bean;
18 | import org.springframework.context.annotation.Configuration;
19 | import org.springframework.context.annotation.Scope;
20 | import org.springframework.context.annotation.ScopedProxyMode;
21 | import org.springframework.security.authentication.RememberMeAuthenticationToken;
22 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
23 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
24 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
25 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
26 | import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
27 | import org.springframework.security.core.Authentication;
28 | import org.springframework.security.core.context.SecurityContextHolder;
29 | import org.springframework.security.core.userdetails.UserDetails;
30 | import org.springframework.security.web.SecurityFilterChain;
31 | import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
32 |
33 |
34 | @Configuration
35 | @EnableWebSecurity
36 | public class SecurityConfig {
37 |
38 |
39 | @Autowired
40 | public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
41 | // to customize with your own authentication provider
42 | auth
43 | .inMemoryAuthentication()
44 | .withUser("user").password("password").roles("USER");
45 | }
46 |
47 | @Bean
48 | public WebSecurityCustomizer webSecurityCustomizer() {
49 | return (web) -> web.ignoring().requestMatchers("/resources/**");
50 | }
51 |
52 |
53 | @Bean
54 | public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
55 | http
56 | .authorizeHttpRequests((authz) -> authz
57 | .requestMatchers("/signup","/about").permitAll()
58 | .requestMatchers("/admin/**").hasRole("ADMIN")
59 | .anyRequest().authenticated())
60 | .formLogin(form -> form
61 | .loginPage("/login")
62 | .permitAll()
63 | );
64 | return http.build();
65 | }
66 |
67 |
68 | /**
69 | * Authenticated user information available as a proxified Spring bean.
70 | *
71 | * Could be inject into beans of scope singleton (ie. @Service or @Controller)
72 | */
73 | @Bean
74 | @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
75 | public UserDetails authenticatedUserDetails() {
76 | SecurityContextHolder.getContext().getAuthentication();
77 | Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
78 | if (authentication != null) {
79 | if (authentication instanceof UsernamePasswordAuthenticationToken) {
80 | return (UserDetails) authentication.getPrincipal();
81 | }
82 | if (authentication instanceof RememberMeAuthenticationToken) {
83 | return (UserDetails) authentication.getPrincipal();
84 | }
85 | }
86 | return null;
87 | }
88 |
89 | @Bean
90 | public HandlerMappingIntrospector mvcHandlerMappingIntrospector() {
91 | return new HandlerMappingIntrospector();
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/src/main/java/com/javaetmoi/sample/config/ServiceConfig.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2014-2017 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 | package com.javaetmoi.sample.config;
15 |
16 | import java.util.ArrayList;
17 | import java.util.List;
18 | import java.util.concurrent.Executor;
19 |
20 | import org.slf4j.Logger;
21 | import org.slf4j.LoggerFactory;
22 | import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
23 | import org.springframework.cache.Cache;
24 | import org.springframework.cache.CacheManager;
25 | import org.springframework.cache.annotation.EnableCaching;
26 | import org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean;
27 | import org.springframework.cache.support.SimpleCacheManager;
28 | import org.springframework.context.annotation.Bean;
29 | import org.springframework.context.annotation.ComponentScan;
30 | import org.springframework.context.annotation.Configuration;
31 | import org.springframework.context.annotation.EnableAspectJAutoProxy;
32 | import org.springframework.scheduling.annotation.AsyncConfigurer;
33 | import org.springframework.scheduling.annotation.EnableAsync;
34 | import org.springframework.scheduling.annotation.EnableScheduling;
35 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
36 |
37 | @Configuration
38 | @EnableAsync
39 | @EnableScheduling
40 | @EnableAspectJAutoProxy
41 | @EnableCaching
42 | @ComponentScan(basePackages = { "com.javaetmoi.sample.service" })
43 | public class ServiceConfig implements AsyncConfigurer {
44 |
45 | private final Logger log = LoggerFactory.getLogger(ServiceConfig.class);
46 |
47 | @Bean
48 | public CacheManager cacheManager() {
49 | SimpleCacheManager cacheManager = new SimpleCacheManager();
50 | List caches = new ArrayList();
51 | // to customize
52 | caches.add(defaultCache());
53 | cacheManager.setCaches(caches);
54 | return cacheManager;
55 | }
56 |
57 | @Bean
58 | public Cache defaultCache() {
59 | ConcurrentMapCacheFactoryBean cacheFactoryBean = new ConcurrentMapCacheFactoryBean();
60 | cacheFactoryBean.setName("default");
61 | cacheFactoryBean.afterPropertiesSet();
62 | return cacheFactoryBean.getObject();
63 |
64 | }
65 |
66 | @Override
67 | public Executor getAsyncExecutor() {
68 | log.debug("Creating Async Task Executor");
69 | ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
70 | // to customize with your requirements
71 | executor.setCorePoolSize(5);
72 | executor.setMaxPoolSize(40);
73 | executor.setQueueCapacity(100);
74 | executor.setThreadNamePrefix("MyExecutor-");
75 | executor.initialize();
76 | return executor;
77 | }
78 |
79 | @Override
80 | public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
81 | // You may customize the handler that manages exceptions thrown during an asynchronous method execution
82 | // See http://www.concretepage.com/spring-4/spring-4-async-exception-handling-with-asyncuncaughtexceptionhandler
83 | return null;
84 | }
85 |
86 | }
87 |
--------------------------------------------------------------------------------
/src/main/java/com/javaetmoi/sample/config/WebMvcConfig.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2014-2017 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 | package com.javaetmoi.sample.config;
15 |
16 | import jakarta.annotation.PostConstruct;
17 |
18 | import org.springframework.beans.factory.annotation.Autowired;
19 | import org.springframework.context.annotation.Bean;
20 | import org.springframework.context.annotation.ComponentScan;
21 | import org.springframework.context.annotation.Configuration;
22 | import org.springframework.context.support.ReloadableResourceBundleMessageSource;
23 | import org.springframework.format.FormatterRegistry;
24 | import org.springframework.web.servlet.ViewResolver;
25 | import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
26 | import org.springframework.web.servlet.config.annotation.EnableWebMvc;
27 | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
28 | import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
29 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
30 | import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
31 | import org.springframework.web.servlet.view.InternalResourceViewResolver;
32 | import org.springframework.web.servlet.view.JstlView;
33 |
34 | @Configuration
35 | @EnableWebMvc
36 | @ComponentScan(basePackages = {"com.javaetmoi.sample.web"})
37 | public class WebMvcConfig implements WebMvcConfigurer {
38 |
39 | private static final int CACHE_PERIOD = 31556926; // one year
40 |
41 | @Autowired
42 | private RequestMappingHandlerAdapter requestMappingHandlerAdapter;
43 |
44 | @PostConstruct
45 | public void init() {
46 | requestMappingHandlerAdapter.setIgnoreDefaultModelOnRedirect(true);
47 | }
48 |
49 | @Bean
50 | public ViewResolver viewResolver() {
51 | // Example: the 'info' view logical name is mapped to the file '/WEB-INF/jsp/info.jsp'
52 | InternalResourceViewResolver bean = new InternalResourceViewResolver();
53 | bean.setViewClass(JstlView.class);
54 | bean.setPrefix("/WEB-INF/jsp/");
55 | bean.setSuffix(".jsp");
56 | return bean;
57 | }
58 |
59 | @Bean(name = "messageSource")
60 | public ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource() {
61 | ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
62 | messageSource.setBasenames("classpath:com/javaetmoi/sample/web/messages");
63 | messageSource.setDefaultEncoding("UTF-8");
64 | return messageSource;
65 | }
66 |
67 | @Override
68 | public void addResourceHandlers(ResourceHandlerRegistry registry) {
69 | // Static ressources from both WEB-INF and webjars
70 | registry
71 | .addResourceHandler("/resources/**")
72 | .addResourceLocations("/resources/")
73 | .setCachePeriod(CACHE_PERIOD);
74 | registry
75 | .addResourceHandler("/webjars/**")
76 | .addResourceLocations("classpath:/META-INF/resources/webjars/")
77 | .setCachePeriod(CACHE_PERIOD);
78 | }
79 |
80 | @Override
81 | public void addViewControllers(ViewControllerRegistry registry) {
82 | registry.addViewController("/about"); // the about page did not required any controller
83 | }
84 |
85 | @Override
86 | public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
87 | // Serving static files using the Servlet container's default Servlet.
88 | configurer.enable();
89 | }
90 |
91 | @Override
92 | public void addFormatters(FormatterRegistry formatterRegistry) {
93 | // add your custom formatters
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/src/main/resources/com/javaetmoi/sample/config/datasource.properties:
--------------------------------------------------------------------------------
1 | jdbc.jndiDataSource=java:comp/env/jdbc/MyDatabase
2 |
3 |
--------------------------------------------------------------------------------
/src/main/resources/com/javaetmoi/sample/config/infrastructure.properties:
--------------------------------------------------------------------------------
1 | jpa.database=H2
2 | jpa.showSql=false
3 | jpa.generateDdl=false
4 |
5 | hibernate.generate_statistics=true
6 | hibernate.dialect=org.hibernate.dialect.H2Dialect
--------------------------------------------------------------------------------
/src/main/resources/jndi.properties:
--------------------------------------------------------------------------------
1 | java.naming.factory.url.pkgs=org.mortbay.naming
2 | java.naming.factory.initial=org.mortbay.naming.InitialContextFactory
--------------------------------------------------------------------------------
/src/main/webapp/WEB-INF/jetty-web.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | java:comp/env/jdbc/MyDatabase
9 |
10 |
11 | jdbc:h2:tcp://localhost/test;USER=sa
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/src/main/webapp/WEB-INF/web.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | Spring JavaConfig Sample
7 |
8 |
9 | contextClass
10 | org.springframework.web.context.support.AnnotationConfigWebApplicationContext
11 |
12 |
13 | spring.profiles.active
14 | javaee
15 |
16 |
17 | contextConfigLocation
18 | com.javaetmoi.sample.config.MainConfig
19 |
20 |
21 |
22 | org.springframework.web.context.ContextLoaderListener
23 |
24 |
25 |
26 |
27 | springSecurityFilterChain
28 | org.springframework.web.filter.DelegatingFilterProxy
29 |
30 |
31 | springSecurityFilterChain
32 | /*
33 | ERROR
34 | REQUEST
35 |
36 |
37 |
38 |
39 | mvc
40 | org.springframework.web.servlet.DispatcherServlet
41 |
42 | contextClass
43 | org.springframework.web.context.support.AnnotationConfigWebApplicationContext
44 |
45 |
46 | contextConfigLocation
47 | com.javaetmoi.sample.config.WebMvcConfig
48 |
49 | 1
50 |
51 |
52 | mvc
53 | /
54 |
55 |
56 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/src/test/java/com/javaetmoi/sample/config/SpringConfigTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2014-2017 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 | package com.javaetmoi.sample.config;
15 |
16 | import org.junit.jupiter.api.Test;
17 | import org.springframework.beans.factory.annotation.Autowired;
18 | import org.springframework.test.context.ActiveProfiles;
19 | import org.springframework.test.context.ContextConfiguration;
20 | import org.springframework.test.context.ContextHierarchy;
21 | import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
22 | import org.springframework.test.context.web.WebAppConfiguration;
23 | import org.springframework.web.context.WebApplicationContext;
24 |
25 | import static org.junit.jupiter.api.Assertions.assertNotNull;
26 |
27 |
28 | @SpringJUnitConfig
29 | @WebAppConfiguration
30 | @ContextHierarchy({
31 | @ContextConfiguration(classes = MainConfig.class),
32 | @ContextConfiguration(classes = WebMvcConfig.class) })
33 | @ActiveProfiles("test")
34 | class SpringConfigTest {
35 |
36 | @Autowired
37 | private WebApplicationContext wac;
38 |
39 | @Test
40 | void springConfiguration() {
41 | assertNotNull(wac);
42 | }
43 | }
--------------------------------------------------------------------------------