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

①application.yml

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

② Annotation

//Add on entity class:
@Alias("value")

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"/>
</bean>
  1. springboot
mybatis:
	mapper-locations:
    	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 --
		sqlSessionFactoryBuilder.build(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="classpath:sql.properties"/>
    <!--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"/>
    </bean>
    <!--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"/>
    </bean>
    <!--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"/>
    </bean>
  1. Spring boot integrates mybatis (there are also jdbc and druid methods). See details Click here to jump)

①application.yml

spring:
  # Connect to database
  datasource:
    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
    password: Lidice.java.717

② 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
*/
@bean
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"/>
</bean>
  1. aop configuration transaction of spring
</bean> 
	<tx:advice id="bankAdvice" transaction-manager="transactionManager"> 		 
		<tx:attributes> 
			<tx:method name="transfer" propagation="REQUIRED"/> 
		</tx:attributes> 
	</tx:advice> 
	<aop:config> 
		<aop:pointcut id="bankPointcut" expression="execution(* *.transfer(..))"/> 	 
		<aop:advisor advice-ref="bankAdvice" pointcut-ref="bankPointcut"/> 
	</aop:config> ...... 
</beans>

3.springboot annotated version transaction

@Service
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());
        companyMapper.insertOne(company);
        personMapper.insertOne(person);
    }
}

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

VIII Register servlet

  1. spring register web xml
 <!--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:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
  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)) {
      out.print(echostr);
    }
  }
}
@SpringBootApplication
public class MyAppliction extends SpringBootServletInitializer {

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

    // Register servlet
    @Bean
    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"/>
    </bean>
  1. springboot also integrates MVC
@Configuration
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{
        @Override
        public View resolveViewName(String s, Locale locale) throws Exception {
            return null;
        }
    }
}

X Garbled code problem

  1. SpringMVC
	<!--Random code filtering-->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

2.springboot

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

More ways Click here to view

Xi Static resource import

  1. springMVC pom.xml
<!--Static resource export-->
<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>
  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
}
<!---->
<mvc:interceptors>
	<mvc:interceptor>
		<!--Block all requests under this request, `/`representative Tomcat Configured root path-->
		<mvc:mapping path="/**"/>
		<bean class="com.lidice.config.MyInterceptor"/>
	</mvc:interceptor>
	
	<mvc:interceptor>
		<!--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"/>
	</mvc:interceptor>
</mvc:interceptors>
  1. springboot
//Custom interceptors -- Translation: Handling interceptions
@Configuration
public class LoginHandlerInterceptor implements HandlerInterceptor {

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

        if(username==null){
            request.setAttribute("msg","No permission, please log in first");
            request.getRequestDispatcher("/login.html").forward(request,response);
            return false;
        }
        return true;
    }
}
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
 
    //Interceptor
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //addPathPatterns: intercepted, excludePathPatterns: not intercepted
        //Chain programming
        registry.addInterceptor(new  LoginHandlerInterceptor())
        .addPathPatterns("/**")
        .excludePathPatterns("/index.html","/","/user/login","/css/**","/img/**","/js/**");            		
    }
}

XIII View jump

  1. springMVC
@Controller
@RequestMapping("/user")
public class UserController {

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

Topics: Java Spring Boot Java framework SSM