spring boot mysql autoconfiguration (#1639)

* spring boot mysql autoconfiguration

* exclude autoconfig from other main classes

* update property condition
This commit is contained in:
lor6 2017-04-20 01:49:09 +03:00 committed by KevinGilmore
parent 87bc04ae98
commit aa08d1262b
21 changed files with 286 additions and 14 deletions

View File

@ -120,6 +120,12 @@
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -165,6 +171,7 @@
<excludes> <excludes>
<exclude>**/*IntegrationTest.java</exclude> <exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude> <exclude>**/*LiveTest.java</exclude>
<exclude>**/AutoconfigurationTest.java</exclude>
</excludes> </excludes>
</configuration> </configuration>
</plugin> </plugin>
@ -190,6 +197,7 @@
<configuration> <configuration>
<excludes> <excludes>
<exclude>**/*LiveTest.java</exclude> <exclude>**/*LiveTest.java</exclude>
<exclude>**/AutoconfigurationTest.java</exclude>
</excludes> </excludes>
<includes> <includes>
<include>**/*IntegrationTest.java</include> <include>**/*IntegrationTest.java</include>
@ -206,6 +214,39 @@
</plugins> </plugins>
</build> </build>
</profile> </profile>
<profile>
<id>autoconfiguration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
<includes>
<include>**/AutoconfigurationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles> </profiles>

View File

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

View File

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

View File

@ -0,0 +1,121 @@
package com.baeldung.autoconfiguration;
import java.util.Arrays;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionMessage.Style;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnResource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
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;
@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(new String[] { "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 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");
for (String className : CLASS_NAMES) {
if (ClassUtils.isPresent(className, context.getClassLoader())) {
return ConditionOutcome.match(message.found("class").items(Style.NORMAL, className));
}
}
return ConditionOutcome.noMatch(message.didNotFind("class", "classes").items(Style.NORMAL, Arrays.asList(CLASS_NAMES)));
}
}
}

View File

@ -0,0 +1,15 @@
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

@ -0,0 +1,27 @@
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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -14,11 +14,13 @@ import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@RestController @RestController
@EnableAutoConfiguration @EnableAutoConfiguration(exclude=MySQLAutoconfiguration.class)
@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.service" }) @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.service" })
public class SpringBootApplication { public class SpringBootApplication {

View File

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

View File

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

View File

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

View File

@ -0,0 +1,28 @@
package com.baeldung.autoconfiguration;
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;
import com.baeldung.autoconfiguration.example.AutoconfigurationApplication;
import com.baeldung.autoconfiguration.example.MyUser;
import com.baeldung.autoconfiguration.example.MyUserRepository;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = AutoconfigurationApplication.class)
@EnableJpaRepositories(basePackages = { "com.baeldung.autoconfiguration.example" })
public class AutoconfigurationTest {
@Autowired
private MyUserRepository userRepository;
@Test
public void whenSaveUser_thenOk() {
MyUser user = new MyUser("user@email.com");
userRepository.save(user);
}
}