upgrade spring-boot project, extract auto-config, remove security

This commit is contained in:
Loredana Crusoveanu
2018-05-06 21:19:41 +03:00
parent c0131fdd8a
commit b4d4d4ec08
63 changed files with 321 additions and 369 deletions

View File

@@ -4,8 +4,6 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
/**
* using the following annotations are equivalent:
* <ul><li>
@@ -16,7 +14,7 @@ import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
* <code>@ServletComponentScan(basePackageClasses = {AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class})</code>
* </li></ul>
*/
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
@SpringBootApplication
@ServletComponentScan("com.baeldung.annotation.servletcomponentscan.components")
public class SpringBootAnnotatedApp {

View File

@@ -3,9 +3,7 @@ package com.baeldung.annotation.servletcomponentscan;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
@SpringBootApplication
@ComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components")
public class SpringBootPlainApp {

View File

@@ -1,106 +0,0 @@
package com.baeldung.autoconfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.*;
import org.springframework.boot.autoconfigure.condition.ConditionMessage.Style;
import org.springframework.context.annotation.*;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.util.ClassUtils;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.Properties;
@Configuration
@ConditionalOnClass(DataSource.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@PropertySource("classpath:mysql.properties")
public class MySQLAutoconfiguration {
@Autowired
private Environment env;
@Bean
@ConditionalOnProperty(name = "usemysql", havingValue = "local")
@ConditionalOnMissingBean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true");
dataSource.setUsername("mysqluser");
dataSource.setPassword("mysqlpass");
return dataSource;
}
@Bean(name = "dataSource")
@ConditionalOnProperty(name = "usemysql", havingValue = "custom")
@ConditionalOnMissingBean
public DataSource dataSource2() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl(env.getProperty("mysql.url"));
dataSource.setUsername(env.getProperty("mysql.user") != null ? env.getProperty("mysql.user") : "");
dataSource.setPassword(env.getProperty("mysql.pass") != null ? env.getProperty("mysql.pass") : "");
return dataSource;
}
@Bean
@ConditionalOnBean(name = "dataSource")
@ConditionalOnMissingBean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan("com.baeldung.autoconfiguration.example");
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
if (additionalProperties() != null) {
em.setJpaProperties(additionalProperties());
}
return em;
}
@Bean
@ConditionalOnMissingBean(type = "JpaTransactionManager")
JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
@ConditionalOnResource(resources = "classpath:mysql.properties")
@Conditional(HibernateCondition.class)
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("mysql-hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("mysql-hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("mysql-hibernate.show_sql") != null ? env.getProperty("mysql-hibernate.show_sql") : "false");
return hibernateProperties;
}
static class HibernateCondition extends SpringBootCondition {
private static final String[] CLASS_NAMES = { "org.hibernate.ejb.HibernateEntityManager", "org.hibernate.jpa.HibernateEntityManager" };
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("Hibernate");
return Arrays.stream(CLASS_NAMES).filter(className -> ClassUtils.isPresent(className, context.getClassLoader())).map(className -> ConditionOutcome.match(message.found("class").items(Style.NORMAL, className))).findAny()
.orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes").items(Style.NORMAL, Arrays.asList(CLASS_NAMES))));
}
}
}

View File

@@ -1,15 +0,0 @@
package com.baeldung.autoconfiguration.example;
import javax.annotation.security.RolesAllowed;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AutoconfigurationApplication {
@RolesAllowed("*")
public static void main(String[] args) {
System.setProperty("security.basic.enabled", "false");
SpringApplication.run(AutoconfigurationApplication.class, args);
}
}

View File

@@ -1,27 +0,0 @@
package com.baeldung.autoconfiguration.example;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class MyUser {
@Id
private String email;
public MyUser() {
}
public MyUser(String email) {
super();
this.email = email;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

View File

@@ -1,7 +0,0 @@
package com.baeldung.autoconfiguration.example;
import org.springframework.data.jpa.repository.JpaRepository;
public interface MyUserRepository extends JpaRepository<MyUser, String> {
}

View File

@@ -2,7 +2,9 @@ package com.baeldung.dynamicvalidation;
import com.baeldung.dynamicvalidation.dao.ContactInfoExpressionRepository;
import com.baeldung.dynamicvalidation.model.ContactInfoExpression;
import org.apache.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.thymeleaf.util.StringUtils;
@@ -13,7 +15,7 @@ import java.util.regex.Pattern;
public class ContactInfoValidator implements ConstraintValidator<ContactInfo, String> {
private static final Logger LOG = Logger.getLogger(ContactInfoValidator.class);
private static final Logger LOG = LogManager.getLogger(ContactInfoValidator.class);
@Autowired
private ContactInfoExpressionRepository expressionRepository;

View File

@@ -5,9 +5,7 @@ import javax.annotation.security.RolesAllowed;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
@SpringBootApplication
public class DynamicValidationApp {
@RolesAllowed("*")
public static void main(String[] args) {

View File

@@ -1,14 +1,10 @@
package com.baeldung.errorhandling;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
@SpringBootApplication(exclude = {MySQLAutoconfiguration.class})
@SpringBootApplication
@ComponentScan(basePackages = "com.baeldung.errorhandling")
public class ErrorHandlingApplication {
@@ -16,11 +12,4 @@ public class ErrorHandlingApplication {
System.setProperty("spring.profiles.active", "errorhandling");
SpringApplication.run(ErrorHandlingApplication.class, args);
}
@Bean(name = "mvcHandlerMappingIntrospector")
public HandlerMappingIntrospector mvcHandlerMappingIntrospector(ApplicationContext context) {
return new HandlerMappingIntrospector(context);
}
}

View File

@@ -1,6 +1,6 @@
package com.baeldung.errorhandling.controllers;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

View File

@@ -5,9 +5,7 @@ import javax.annotation.security.RolesAllowed;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
@SpringBootApplication
public class FailureAnalyzerApplication {
@RolesAllowed("*")
public static void main(String[] args) {

View File

@@ -6,9 +6,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
@SpringBootApplication(scanBasePackages = { "com.baeldung.git" }, exclude = MySQLAutoconfiguration.class)
@SpringBootApplication(scanBasePackages = { "com.baeldung.git" })
public class CommitIdApplication {
public static void main(String[] args) {
SpringApplication.run(CommitIdApplication.class, args);

View File

@@ -5,9 +5,7 @@ import javax.annotation.security.RolesAllowed;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
@SpringBootApplication
public class InternationalizationApp {
@RolesAllowed("*")
public static void main(String[] args) {

View File

@@ -7,13 +7,13 @@ import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
@Configuration
@ComponentScan(basePackages = "com.baeldung.internationalization.config")
public class MvcConfig extends WebMvcConfigurerAdapter {
public class MvcConfig implements WebMvcConfigurer {
@Bean
public LocaleResolver localeResolver() {

View File

@@ -3,9 +3,7 @@ package com.baeldung.intro;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);

View File

@@ -1,16 +1,17 @@
package com.baeldung.rss;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;
@Component
public class CustomContainer implements EmbeddedServletContainerCustomizer {
public class CustomContainer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setPort(8080);
container.setContextPath("");
public void customize(ConfigurableServletWebServerFactory factory) {
factory.setContextPath("");
factory.setPort(8080);
}
}

View File

@@ -1,13 +1,12 @@
package com.baeldung.rss;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import javax.annotation.security.RolesAllowed;
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
@SpringBootApplication
@ComponentScan(basePackages = "com.baeldung.rss")
public class RssApp {

View File

@@ -5,7 +5,7 @@ import java.time.LocalDateTime;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

View File

@@ -3,11 +3,9 @@ package com.baeldung.servlets;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
@SpringBootApplication
public class ApplicationMain extends SpringBootServletInitializer {
public static void main(String[] args) {

View File

@@ -1,17 +1,17 @@
package com.baeldung.servlets.configuration;
import org.springframework.boot.web.support.ErrorPageFilter;
import org.springframework.boot.web.servlet.support.ErrorPageFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.PathResourceResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
public class WebMvcConfigure extends WebMvcConfigurerAdapter {
public class WebMvcConfigure implements WebMvcConfigurer {
@Bean
public ViewResolver getViewResolver() {

View File

@@ -9,8 +9,8 @@ import org.springframework.context.annotation.Configuration;
public class SpringRegistrationBeanServlet {
@Bean
public ServletRegistrationBean genericCustomServlet() {
ServletRegistrationBean bean = new ServletRegistrationBean(new GenericCustomServlet(), "/springregistrationbeanservlet/*");
public ServletRegistrationBean<GenericCustomServlet> genericCustomServlet() {
ServletRegistrationBean<GenericCustomServlet> bean = new ServletRegistrationBean<>(new GenericCustomServlet(), "/springregistrationbeanservlet/*");
bean.setLoadOnStartup(1);
return bean;
}

View File

@@ -1,7 +1,7 @@
package com.baeldung.servlets.servlets.springboot.embedded;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -9,8 +9,8 @@ import org.springframework.context.annotation.Configuration;
public class EmbeddedTomcatExample {
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
public ConfigurableServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
return tomcat;
}
}

View File

@@ -1,16 +1,13 @@
package com.baeldung.shutdown;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.system.ApplicationPidFileWriter;
import org.springframework.boot.context.ApplicationPidFileWriter;
import org.springframework.context.ConfigurableApplicationContext;
import javax.annotation.security.RolesAllowed;
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
@SpringBootApplication
public class Application {
public static void main(String[] args) {
@@ -24,7 +21,7 @@ public class Application {
private static void closeApplication() {
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(Application.class).web(false).run();
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(Application.class).web(WebApplicationType.NONE).run();
System.out.println("Spring Boot application started");
ctx.getBean(TerminateBean.class);
ctx.close();
@@ -32,7 +29,7 @@ public class Application {
private static void exitApplication() {
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(Application.class).web(false).run();
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(Application.class).web(WebApplicationType.NONE).run();
int exitCode = SpringApplication.exit(ctx, () -> {
// return the error code
@@ -45,7 +42,7 @@ public class Application {
}
private static void writePID() {
SpringApplicationBuilder app = new SpringApplicationBuilder(Application.class).web(false);
SpringApplicationBuilder app = new SpringApplicationBuilder(Application.class).web(WebApplicationType.NONE);
app.build().addListeners(new ApplicationPidFileWriter("./bin/shutdown.pid"));
app.run();
}

View File

@@ -1,6 +1,7 @@
package com.baeldung.toggle;
import org.apache.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
@@ -10,7 +11,7 @@ import org.springframework.stereotype.Component;
@Component
public class FeaturesAspect {
private static final Logger LOG = Logger.getLogger(FeaturesAspect.class);
private static final Logger LOG = LogManager.getLogger(FeaturesAspect.class);
@Around(value = "@within(featureAssociation) || @annotation(featureAssociation)")
public Object checkAspect(ProceedingJoinPoint joinPoint, FeatureAssociation featureAssociation) throws Throwable {

View File

@@ -11,7 +11,7 @@ public class SalaryService {
@FeatureAssociation(value = MyFeatures.EMPLOYEE_MANAGEMENT_FEATURE)
public void increaseSalary(long id) {
Employee employee = employeeRepository.findOne(id);
Employee employee = employeeRepository.findById(id).orElse(null);
employee.setSalary(employee.getSalary() + employee.getSalary() * 0.1);
employeeRepository.save(employee);
}

View File

@@ -5,9 +5,7 @@ import javax.annotation.security.RolesAllowed;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
@SpringBootApplication
public class ToggleApplication {
@RolesAllowed("*")
public static void main(String[] args) {

View File

@@ -6,9 +6,7 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
@SpringBootApplication
@ComponentScan(basePackages = "com.baeldung.utils")
public class UtilsApplication {

View File

@@ -3,9 +3,7 @@ package com.baeldung.webjar;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
@SpringBootApplication
public class WebjarsdemoApplication {
public static void main(String[] args) {

View File

@@ -4,9 +4,7 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
@SpringBootApplication
public class Application {
private static ApplicationContext applicationContext;

View File

@@ -7,12 +7,12 @@ import org.baeldung.boot.web.resolver.HeaderVersionArgumentResolver;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
public class WebConfig implements WebMvcConfigurer {
@Override
public void addArgumentResolvers(final List<HandlerMethodArgumentResolver> argumentResolvers) {

View File

@@ -1,6 +1,6 @@
package org.baeldung.common.error;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
public class MyCustomErrorController implements ErrorController {

View File

@@ -1,20 +1,20 @@
package org.baeldung.common.properties;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
@Component
public class MyServletContainerCustomizationBean implements EmbeddedServletContainerCustomizer {
public class MyServletContainerCustomizationBean implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
public MyServletContainerCustomizationBean() {
}
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
public void customize(ConfigurableServletWebServerFactory container) {
container.setPort(8084);
container.setContextPath("/springbootapp");

View File

@@ -4,10 +4,9 @@ import com.baeldung.graphql.GraphqlConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
import org.springframework.context.annotation.Import;
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
@SpringBootApplication
@Import(GraphqlConfiguration.class)
public class DemoApplication {

View File

@@ -2,10 +2,9 @@ package org.baeldung.demo.boottest;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
@Transactional
@@ -13,8 +12,6 @@ public interface EmployeeRepository extends JpaRepository<Employee, Long> {
public Employee findByName(String name);
public Employee findById(Long id);
public List<Employee> findAll();
}

View File

@@ -2,10 +2,9 @@ package org.baeldung.demo.boottest;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
@@ -16,7 +15,7 @@ public class EmployeeServiceImpl implements EmployeeService {
@Override
public Employee getEmployeeById(Long id) {
return employeeRepository.findById(id);
return employeeRepository.findById(id).orElse(null);
}
@Override

View File

@@ -12,7 +12,7 @@ public class FooService {
private FooRepository fooRepository;
public Foo getFooWithId(Integer id) throws Exception {
return fooRepository.findOne(id);
return fooRepository.findById(id).orElse(null);
}
public Foo getFooWithName(String name) {

View File

@@ -1,35 +0,0 @@
package org.baeldung.endpoints;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.stereotype.Component;
@Component
public class CustomEndpoint implements Endpoint<List<String>> {
public CustomEndpoint() {
}
public String getId() {
return "customEndpoint";
}
public boolean isEnabled() {
return true;
}
public boolean isSensitive() {
return true;
}
public List<String> invoke() {
// Your logic to display the output
List<String> messages = new ArrayList<String>();
messages.add("This is message 1");
messages.add("This is message 2");
return messages;
}
}

View File

@@ -1,23 +0,0 @@
package org.baeldung.endpoints;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;
import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.stereotype.Component;
@Component
public class ListEndpoints extends AbstractEndpoint<List<Endpoint>> {
private List<Endpoint> endpoints;
@Autowired
public ListEndpoints(List<Endpoint> endpoints) {
super("listEndpoints");
this.endpoints = endpoints;
}
public List<Endpoint> invoke() {
return this.endpoints;
}
}

View File

@@ -1,22 +0,0 @@
package org.baeldung.endpoints;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class MyHealthCheck implements HealthIndicator {
public Health health() {
int errorCode = check(); // perform some specific health check
if (errorCode != 0) {
return Health.down().withDetail("Error Code", errorCode).withDetail("Description", "You custom MyHealthCheck endpoint is down").build();
}
return Health.up().build();
}
public int check() {
// Your logic to check health
return 1;
}
}

View File

@@ -4,7 +4,6 @@ import org.baeldung.boot.controller.servlet.HelloWorldServlet;
import org.baeldung.boot.controller.servlet.SpringHelloWorldServlet;
import org.baeldung.common.error.SpringHelloServletRegistrationBean;
import org.baeldung.common.resources.ExecutorServiceExitCodeGenerator;
import org.baeldung.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -14,24 +13,18 @@ import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@RestController
@EnableAutoConfiguration(exclude = MySQLAutoconfiguration.class)
@EnableAutoConfiguration
@ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.boot.config" })
public class SpringBootApplication {
private static ApplicationContext applicationContext;
@Autowired
private LoginService service;
@RequestMapping("/")
String home() {
service.login("admin", "admin".toCharArray());
return "TADA!!! You are in Spring Boot Actuator test application.";
}

View File

@@ -4,9 +4,7 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
@EnableAutoConfiguration(exclude = MySQLAutoconfiguration.class)
@EnableAutoConfiguration
@ComponentScan(basePackageClasses = ConfigProperties.class)
public class ConfigPropertiesDemoApplication {
public static void main(String[] args) {

View File

@@ -1,5 +0,0 @@
package org.baeldung.service;
public interface LoginService {
public boolean login(String userName, char[] password);
}

View File

@@ -1,29 +0,0 @@
package org.baeldung.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.stereotype.Service;
@Service
public class LoginServiceImpl implements LoginService {
private CounterService counterService;
@Autowired
public LoginServiceImpl(CounterService counterService) {
this.counterService = counterService;
}
public boolean login(String userName, char[] password) {
boolean success;
if (userName.equals("admin") && "secret".toCharArray().equals(password)) {
counterService.increment("counter.login.success");
success = true;
} else {
counterService.increment("counter.login.failure");
success = false;
}
return success;
}
}

View File

@@ -7,10 +7,8 @@ import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
@EntityScan(basePackageClasses = Foo.class)
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
@SpringBootApplication
public class Application {
public static void main(String[] args) {
System.setProperty("spring.config.name", "exception");

View File

@@ -1,6 +1,7 @@
package org.baeldung.websocket.client;
import org.apache.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.simp.stomp.StompSession;
@@ -18,7 +19,7 @@ import java.lang.reflect.Type;
*/
public class MyStompSessionHandler extends StompSessionHandlerAdapter {
private Logger logger = Logger.getLogger(MyStompSessionHandler.class);
private Logger logger = LogManager.getLogger(MyStompSessionHandler.class);
@Override
public void afterConnected(StompSession session, StompHeaders connectedHeaders) {

View File

@@ -1,3 +0,0 @@
org.springframework.boot.diagnostics.FailureAnalyzer=com.baeldung.failureanalyzer.MyBeanNotOfRequiredTypeFailureAnalyzer
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.baeldung.autoconfiguration.MySQLAutoconfiguration

View File

@@ -1,5 +0,0 @@
usemysql=local
mysql-hibernate.dialect=org.hibernate.dialect.MySQLDialect
mysql-hibernate.show_sql=true
mysql-hibernate.hbm2ddl.auto=create-drop

View File

@@ -1,27 +0,0 @@
package com.baeldung.autoconfiguration;
import com.baeldung.autoconfiguration.example.AutoconfigurationApplication;
import com.baeldung.autoconfiguration.example.MyUser;
import com.baeldung.autoconfiguration.example.MyUserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = AutoconfigurationApplication.class)
@EnableJpaRepositories(basePackages = { "com.baeldung.autoconfiguration.example" })
public class AutoconfigurationIntegrationTest {
@Autowired
private MyUserRepository userRepository;
@Test
public void whenSaveUser_thenOk() {
MyUser user = new MyUser("user@email.com");
userRepository.save(user);
}
}

View File

@@ -4,9 +4,9 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;

View File

@@ -16,7 +16,7 @@ import com.baeldung.servletinitializer.WarInitializerApplication.WarInitializerC
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = WarInitializerController.class)
public class WarInitializerApplicationTest {
public class WarInitializerApplicationIntegrationTest {
@Autowired
private MockMvc mockMvc;

View File

@@ -47,7 +47,7 @@ public class ToggleIntegrationTest {
mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200));
emp = employeeRepository.findOne(1L);
emp = employeeRepository.findById(1L).orElse(null);
assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5);
}
@@ -60,7 +60,7 @@ public class ToggleIntegrationTest {
mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200));
emp = employeeRepository.findOne(1L);
emp = employeeRepository.findById(1L).orElse(null);
assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5);
}
}

View File

@@ -22,7 +22,7 @@ public class SpringBootH2IntegrationTest {
@Test
public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test"));
GenericEntity foundEntity = genericEntityRepository.findOne(genericEntity.getId());
GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null);
assertNotNull(foundEntity);
assertEquals(genericEntity.getValue(), foundEntity.getValue());
}

View File

@@ -21,7 +21,7 @@ public class SpringBootJPAIntegrationTest {
@Test
public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test"));
GenericEntity foundEntity = genericEntityRepository.findOne(genericEntity.getId());
GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null);
assertNotNull(foundEntity);
assertEquals(genericEntity.getValue(), foundEntity.getValue());
}

View File

@@ -24,7 +24,7 @@ public class SpringBootProfileIntegrationTest {
@Test
public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test"));
GenericEntity foundEntity = genericEntityRepository.findOne(genericEntity.getId());
GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null);
assertNotNull(foundEntity);
assertEquals(genericEntity.getValue(), foundEntity.getValue());
}

View File

@@ -43,13 +43,13 @@ public class EmployeeRepositoryIntegrationTest {
Employee emp = new Employee("test");
entityManager.persistAndFlush(emp);
Employee fromDb = employeeRepository.findById(emp.getId());
Employee fromDb = employeeRepository.findById(emp.getId()).orElse(null);
assertThat(fromDb.getName()).isEqualTo(emp.getName());
}
@Test
public void whenInvalidId_thenReturnNull() {
Employee fromDb = employeeRepository.findById(-11L);
Employee fromDb = employeeRepository.findById(-11l).orElse(null);
assertThat(fromDb).isNull();
}

View File

@@ -50,9 +50,9 @@ public class EmployeeServiceImplIntegrationTest {
Mockito.when(employeeRepository.findByName(john.getName())).thenReturn(john);
Mockito.when(employeeRepository.findByName(alex.getName())).thenReturn(alex);
Mockito.when(employeeRepository.findByName("wrong_name")).thenReturn(null);
Mockito.when(employeeRepository.findById(john.getId())).thenReturn(john);
Mockito.when(employeeRepository.findById(john.getId()).orElse(null)).thenReturn(john);
Mockito.when(employeeRepository.findAll()).thenReturn(allEmployees);
Mockito.when(employeeRepository.findById(-99L)).thenReturn(null);
Mockito.when(employeeRepository.findById(-99L).orElse(null)).thenReturn(null);
}
@Test