Comparison of some details between SSM and SpringBoot

Posted by dahwan on Mon, 20 Dec 2021 22:36:28 +0100

Comparison between SSM and SpringBoot

I Alias entity class bean s

  1. Mybatis
    Use the < typealiases > label in the configuration file
  2. spring
    Use the < alias > tag in the configuration file or the < name > attribute in bean notes
  3. springboot


	type-aliases-package: com.lidice.**

② Annotation

//Add on entity class:

II Mapper register mapper

  1. Mybatis
    Use the < mappers > tag in the configuration file
  2. spring

① Integrate mybatis

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="mapperLocations" value="classpath:com/lidice/mapper/*.xml"/>
  1. springboot
    	classpath: mybatis/mapper/*.xml

III Get database connection

  1. Mybatis
		//First in mybatis Configuring database information in XML
		String resource = "mybatis.xml"; -- 
		Resources.getResourceAsStream(resouce)	obtain is -- obtain sqlSessionFactory --
		sqlSessionFactory.openSession() obtain sqlSession --
		sqlSession.getMapper(Class c) Get current Mapper Object of class --
		Last call method
  1. springMVC
<!--Read database configuration properties file-->
    <context:property-placeholder location=""/>
    <!--c3p0 Database connection pool connection database-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>

        <property name="autoCommitOnClose" value="false"/>
        <property name="checkoutTimeout" value="10000"/>
        <property name="acquireRetryAttempts" value="2"/>
    <!--establish sqlSession Factory, get database connection-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--obtain dataSource Connection pool-->
        <property name="dataSource" ref="dataSource"/>
        <!--integration Mybatis configuration file-->
        <property name="configLocation" value="classpath:mybatis.xml"/>
    <!--use spring of api application sqlSessionFactory establish sqlSession;
        And will dao Class injection under package spring in-->
    <bean id="scannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="com.lidice.mapper"/>
  1. Spring boot integrates mybatis (there are also jdbc and druid methods). See details Click here to jump)


  # Connect to database
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    username: root

② Then

Import dependency - mybatis register mapper, alias configuration - pojo, mapper, service, controller - access

IV Enable annotation support

  1. spring uses < context: annotation config / > to enable annotation support
  2. Spring MVC uses < MVC: annotation driven / > to enable annotation support
  3. Spring boot enables annotation support by default

V Configuration file xml to configuration class annotation

  1. SSM uses xml configuration file to enable functions
  2. Spring boot uses the configuration annotation to replace xml configuration files with configuration classes

Vi Comparison of injected bean s

  1. SSM directly configures < bean id = "" class = "" / > in xml to inject beans
  2. : open < context: component scan base = "com. Lidice" / > in the SSM configuration file, and use the Component annotation on the class to be injected
  3. springboot uses @ component @bean, etc
new The value of is equivalent to the class attribute in the SSM configuration file
 The method name is equivalent to the id attribute in the SSM configuration file
public User user(){
	return new User();

Supplement: instead of * * @ SpringBootApplication * * of springboot
@Configuration: declare that the main startup class is also javaConfig
@EnableAutoConfiguration: automatically scan custom and extended configuration classes
@ComponentScan: scan@ Component@bean Automatic injection class

VII affair

  1. spring declarative transaction:
<!--to service Add declarative transaction to layer-->
<bean id="transaction" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
  1. aop configuration transaction of spring
	<tx:advice id="bankAdvice" transaction-manager="transactionManager"> 		 
			<tx:method name="transfer" propagation="REQUIRED"/> 
		<aop:pointcut id="bankPointcut" expression="execution(* *.transfer(..))"/> 	 
		<aop:advisor advice-ref="bankAdvice" pointcut-ref="bankPointcut"/> 
	</aop:config> ...... 

3.springboot annotated version transaction

public class PersonService {
    @Resource //byName auto assemble first
    private PersonMapper personMapper;
    @Autowird //First byType automatic assembly
    private CompanyMapper companyMapper;

	rollbackFor: The exceptions that trigger rollback are RuntimeException and Error by default
	isolation: The isolation level of transactions. The default is isolation Default is the default isolation level of the database itself. For example, MySQL is ISOLATION_REPEATABLE_READ repeatable				
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public void saveOne(Person person) {
        Company company = new Company();
        company.setName("tenmao:" + person.getName());

@EnableTransactionManagement is added to the main startup class (or not)

VIII Register servlet

  1. spring register web xml

  1. springboot is also user-defined, because the default server Port is set to route plus port

① Configuration class mode

public class WeChatServlet extends HttpServlet {
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
                        throws ServletException, IOException {

    String signature = req.getParameter("signature");
    String timestamp = req.getParameter("timestamp");
    String nonce = req.getParameter("nonce");
    String echostr = req.getParameter("echostr");
    PrintWriter out = resp.getWriter();
    if (ValidUtil.checkSignature(signature, timestamp, nonce)) {
public class MyAppliction extends SpringBootServletInitializer {

    public static void main(String[] args) {, args);
    // This configuration is packaged as a war package before it can be used under tomcat   
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
       return application.sources(MyApplicaitioni.class);

    // Register servlet
    public ServletRegistrationBean weChatValid(){
      //The first parameter is the WeChatServlet instance created in step 1, and the second parameter is its corresponding path, which is equivalent to web URL pattern when configured in XML.
      return new ServletRegistrationBean(new WeChatServlet(), "/weChatValid");

② Annotated version

//Annotation implementation
@WebServlet(urlPatterns = "/weChatValid", description = "Wechat interface verification")
public class WeChatServlet extends HttpServlet { 
	//... ditto

@ServletComponentScan / / add this annotation on the main startup class

1. Draw inferences from one example: the Filter registration, Listener registration and Servlet registration of spring boot are the same. Since the annotation corresponding to the Servlet is @ WebServlet, the Filter and Listener are... (guess), but they all use @ servletcomponentscan on the main class (this is a bit unreasonable ~)

IX view resolver

  1. springMVC
 <!--view resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/book/"/>
        <property name="suffix" value=".jsp"/>
  1. springboot also integrates MVC
public class MyMvcConfig implements WebMvcConfigurer {
    @Bean //Put in bean
    public ViewResolver myViewResolver(){
        return new MyViewResolver();
    //When we write a static inner class, the view parser needs to implement the ViewResolver interface
    private static class MyViewResolver implements ViewResolver{
        public View resolveViewName(String s, Locale locale) throws Exception {
            return null;

X Garbled code problem

  1. SpringMVC
	<!--Random code filtering-->


#springboot 1.4.2 start providing item codes in this way
			charset: utf-8
			enabled: true
			force: true

More ways Click here to view

Xi Static resource import

  1. springMVC pom.xml
<!--Static resource export-->
  1. springboot has been automatically assembled

XII Interceptor

  1. springMVC
public class MyInterceptor implements HandlerInterceptor(){
	//Override the perHandle method
	//Most of the content is to verify whether there is a username key in the session
	//Finally, return TRUE indicates release. By default, the search will continue for the next filter class
		<!--Block all requests under this request, `/`representative Tomcat Configured root path-->
		<mvc:mapping path="/**"/>
		<bean class="com.lidice.config.MyInterceptor"/>
		<!--Directly when accessing this request path return true Release,It will override the above operations separately-->
		<mvc:mapping path="/user/**"/>
		<bean class="com.lidice.config.LoginInterceptor"/>
  1. springboot
//Custom interceptors -- Translation: Handling interceptions
public class LoginHandlerInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object username = request.getSession().getAttribute("username");

            request.setAttribute("msg","No permission, please log in first");
            return false;
        return true;
public class MyMvcConfig implements WebMvcConfigurer {
    public void addInterceptors(InterceptorRegistry registry) {
        //addPathPatterns: intercepted, excludePathPatterns: not intercepted
        //Chain programming
        registry.addInterceptor(new  LoginHandlerInterceptor())

XIII View jump

  1. springMVC
public class UserController {

    @RequestMapping(value = "/register",produces = "text/html;charset=UTF-8")
    public String register(Model model){
        return "index";
  1. springboot
public class MyMvcConfig implements WebMvcConfigurer {
    //View jump
    public void addViewControllers(ViewControllerRegistry registry) {
        //When accessing "/", jump to "index", and the parameters behind are equivalent to the return page

Topics: Java Spring Boot Java framework SSM