In the process of transferring SpringMVC project to Springboot, the following things were mainly done
In addition to introducing what and how to do it, this article will have a lot of unnecessary nonsense. For some discussions on the principle, you should also know the reason.
Profile configuration
In traditional Spring projects, the configuration method of multiple profiles is to write multiple profiles into the pom.xml file, and then preload the selected profile environment by executing a maven file before starting the project. After loading, when executing the project, it will decide which .properties file to load into the global variable based on the loaded environment.
And managing multiple profiles in Springboot is very simple.
You can select profile when running the jar package using the command line
java -jar example.jar --spring.profiles.active=test
Or configure it in the global configuration application.properties
Add spring.profiles.active=test in application.properties
Both of the above methods can start the "test" profile, the former has higher priority in execution than the latter.
(By the way, in Springboot, these two methods essentially use the "external configuration" method to edit and replace the Environment)
In addition, each independent profiles are configured in the format "application-xxx.properties" for each different environment, for example:
When we need to test whether the profile is loaded normally, we can write it in the corresponding .properties file
server.port=9080
You can see whether this port has been started at startup.
Here you can mention the order in which Springboot loads configuration files
Global variables are read from properties file
In the previous section, we wrote the properties configuration for different environments. Here we will write about if these properties are written into global variables, which is convenient for direct calls in other places later.
/** * Global variable*/public class Global { public static String examplePath; @Value("${example_path}") public void setExamplePath(String example) { Global.examplePath = examplePath; }} In this way, we will put the .properties file in the
example_path=http://localhost:9090
This property is read into the global variable.
Data source and Mybatis configuration
In traditional Spring project, use Mybatis to connect to the database
All of this is configured in the XML configuration file, which is quite cumbersome. In Springboot, try to avoid such xml configuration.
Mybatis has now provided support for Springboot. We only need to add the MyBatis-Spring-Boot-Starter dependency, and it will do the following for us:
So, in the Mybatis configuration of Springboot, we need to do the following:
Fill in the database information in application-{profile}.properties, for example:
spring.datasource.url=jdbc:oracle:thin:@//localhost:1234/examplespring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriverspring.datasource.maxActive=10spring.datasource.maxIdle=5spring.datasource.maxWait=-1
In this way, we register the datasource bean in the Spring context.
Create a MybatisConfig file and replace xml with java:
/** * Created by WuTaoyu on 2017/12/7. */@Configuration@EnableTransactionManagement@MapperScan("com.example.db.dao")public class MybatisConfig { @Autowired private DataSource dataSource; @Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactoryBean() { SqlSessionFactoryBean sqlsession = new SqlSessionFactoryBean(); sqlsession.setDataSource(dataSource); try { //Add XML directory ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sqlsession.setMapperLocations(resolver.getResources("classpath:mapping/*.xml")); return sqlsession.getObject(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } @Bean public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } @Bean public PlatformTransactionManager annotationDrivenTransactionManager() { return new DataSourceTransactionManager(dataSource); } @Bean(name = "exampleSequence") public OracleSequenceMaxValueIncrementer exampleSequenceBean(){ OracleSequenceMaxValueIncrementer exampleSequence = new OracleSequenceMaxValueIncrementer(); exampleSequence.setIncrementerName("EXAMPLE_SEQ"); exampleSequence.setDataSource(dataSource); return exampleSequence; }} @MapperScan is to scan the mapper below this package.
In addition, the location of mapper.xml here is to create a mapping folder under the resource folder and place it below.
The function here is similar to XML. It is to describe the traditional XML expression method in .java files, and essentially inject datasource step by step.
Since the example uses an oracle database, the last exampleSequence is an example to illustrate how to add a sequence.
Annotation of interfaces to all mappers @Mapper
For example:
@Mapperpublic interface UserMapper { ...} Log file configuration
Logback supports external configuration in the form of properties, but for relatively detailed configurations, it is still necessary to use XML configuration.
In order for the xml file to read some paths from the .properties file, static configurations that may require frequent modification, it is necessary to configure it in logback-spring.xml
<property resource="application.properties" /> <property name="log.root.level" value="${log.root.level}" /> <property name="log.path" value="${log.path}" /> <property name="log.moduleName" value="${log.module}" /> This way you can put the application.properties file in the
log.path=/home/logs/examplelog.root.level=INFOlog.module=example
Read it into logback-spring.xml and then call it.
WebConfig configuration
The main function of WebConfig is to replace web.xml and spring-mvc.xml for some basic configuration.
1. About web.xml
Traditional Spring projects all configure a web.xml file. The function of this file is: when we put the war package into the application container (such as tomcat) to run, the container will load filter (filter), servlet, error-page, welcome-file-list, listener (listener), context-param (context parameters), resource-ref (resource configuration) and other configurations according to web.xml.
The listener including the ContextLoaderListener is loaded here to automatically assemble the configuration information of the ApplicationContext when starting the container.
<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
This ApplicationContext is the core of Spring IOC (inherited from BeanFactory), and all singleton beans will be instantiated at this time.
Also, a very important DispatcherServlet in SpringMVC is also loaded here, and it is determined which xml file to configure the DispatcherServlet.
<servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <!--<async-supported>true</async-supported>--></servlet>
2. About spring-mvc.xml
spring-mvc.xml is a SpringMVC configuration file. Here we can configure beans that need to be customized, such as ViewResolver, multipartResolver, HTTP message converter, custom interceptor, etc.
All of the above has nothing to do with Springboot, mainly to know the reason and why. If you are not interested, you can ignore it.
Let’s talk about Springboot configuration. Springboot has a saying that "convention is better than configuration", which means trying to use the agreed method, rather than specifically targeted configuration (configuration when special configuration is required).
After introducing the "out of the box" dependency of spring-boot-starter-web, spring-boot-starter-web contains a spring-boot-autoconfigure.
With this dependency, you can use the @EnableAutoCongiguration annotation. This annotation will guess the Spring configuration you need based on the introduced dependencies and help you configure it. Because spring-boot-starter-web has been introduced, this annotation will configure the web-related configuration.
In addition, the @EnableAutoCongiguration annotation has been included in the @SpringBootApplication annotation. So just annotate @SpringBootApplication on the startup class ExampleServerApplication and you can automatically configure the web to configure it.
Of course, we may have some special configurations, and at this time we can create a WebConfig to customize
/** * Created by WuTaoyu on 2017/12/8. */@Configurationpublic class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(marshallingHttpMessageConverter()); } public MarshallingHttpMessageConverter marshallingHttpMessageConverter(){ MarshallingHttpMessageConverter marshallingHttpMessageConverter = new MarshallingHttpMessageConverter(); List<MediaType> mediaTypes = new ArrayList<MediaType>(); mediaTypes.add(MediaType.TEXT_XML); mediaTypes.add(MediaType.APPLICATION_XML); XStreamMarshaller xStreamMarshaller=new XStreamMarshaller(); marshallingHttpMessageConverter.setSupportedMediaTypes(mediaTypes); marshallingHttpMessageConverter.setMarshaller(xStreamMarshaller); marshallingHttpMessageConverter.setUnmarshaller(xStreamMarshaller); return marshallingHttpMessageConverter; } //Configuration file upload @Bean(name = {"multipartResolver"}) public MultipartResolver multipartResolver(){ CommonsMultipartResolver commonsMultipartResolver=new CommonsMultipartResolver(); commonsMultipartResolver.setDefaultEncoding("utf-8"); commonsMultipartResolver.setMaxUploadSize(10485760000L); commonsMultipartResolver.setMaxInMemorySize(40960); return commonsMultipartResolver; } //Exception handling @Bean public ExceptionHandler exceptionResolver(){ ExceptionHandler exceptionHandler = new ExceptionHandler(); return exceptionHandler; } //Interceptor @Override public void addInterceptors(InterceptorRegistry registry){ registry.addInterceptor(new LogInterceptor()).addPathPatterns("/**"); super.addInterceptors(registry); }}I did a few things in this sample file:
Remove excess bean injection
This is a distraction, but it is also one of the problems I actually encountered.
When actually running Springboot project, I found some problems that did not report errors in traditional Spring projects, which are unnecessary bean injection.
In traditional Spring projects, there is no error, but in Springboot projects, it is reported. I guess it is because when the class method injected to bean is given in a relatively simple way, it will be repeated with some beans automatically configured by Springboot itself, and an error will be reported.
So, remove some beans that do not need to be injected.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.