【Java从零到架构师第③季】【36】SSM纯注解整合

【Java从零到架构师第③季】【36】SSM纯注解整合,第1张

【Java从零到架构师第③季】【36】SSM纯注解整合

持续学习&持续更新中…

守破离


【Java从零到架构师第③季】【36】SSM纯注解整合

纯注解—基本实现

Initializer取代web.xmlSpringConfiguration(父容器)SpringConfiguration(子容器)controller、service、dao代码 纯注解—配置静态资源纯注解—配置拦截器纯注解—ViewResolver纯注解—路径后缀匹配纯注解—响应乱码纯注解—请求乱码纯注解—Converter纯注解—MultipartResolver纯注解—Initializer的本质Initializer取代web.xml—直接实现WebApplicationInitializer参考

纯注解—基本实现 Initializer取代web.xml

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    
    @Override
    protected Class[] getRootConfigClasses() {
        return new Class[]{SpringConfiguration.class};
    }

    
    @Override
    protected Class[] getServletConfigClasses() {
        return new Class[]{SpringMVCConfiguration.class};
    }

    
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}
SpringConfiguration(父容器)

main.properties:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test_mybatis?useSSL=false
jdbc.username=root
jdbc.password=root

mybatis.typeAliasesPackage=programmer.lp.domain
mybatis.mapperScanPackage=programmer.lp.dao
mybatis.configLocation=mybatis-config.xml

SpringConfiguration:

@PropertySource("classpath:main.properties")
@MapperScan("${mybatis.mapperScanPackage}")
@ComponentScan("programmer.lp.service")
@EnableTransactionManagement
public class SpringConfiguration {
    @Value("${jdbc.driverClassName}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Value("${mybatis.typeAliasesPackage}")
    private String typeAliasesPackage;
    @Value("${mybatis.configLocation}")
    private String configLocation;

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
        Resource location = new ClassPathResource(configLocation);
        sqlSessionFactoryBean.setConfigLocation(location);
        return sqlSessionFactoryBean;
    }

    @Bean
    public TransactionManager transactionManager(DataSource dataSource) {
        DataSourceTransactionManager manager = new DataSourceTransactionManager();
        manager.setDataSource(dataSource);
        return manager;
    }
}
SpringConfiguration(子容器)
@ComponentScan("programmer.lp.controller")
@EnableWebMvc
public class SpringMVCConfiguration {

}
controller、service、dao代码

dao:

public interface SkillDao {
    @Insert("INSERT INTO skill(name, level) VALUES(#{name}, #{level})")
    @SelectKey(statement = "SELECT LAST_INSERT_ID()",
            keyProperty = "id",
            keyColumn = "id",
            before = false,
            resultType = Integer.class)
    boolean insert(Skill skill);

    @Delete(("DELETE FROM skill WHERe id = #{id}"))
    boolean delete(Integer id);

    @Update("UPDATE skill SET name = #{name}, level = #{level} WHERe id = #{id}")
    boolean update(Skill skill);

    @Select("SELECT id, created_time, name, level FROM skill WHERe id = #{id}")
    Skill get(Integer id);

    @Select("SELECT id, created_time, name, level FROM skill")
    List list();
}

service:

@Service
@Transactional
public class SkillServiceImpl implements SkillService {
    @Autowired
    private SkillDao dao;

    @Override
    public boolean remove(Integer id) {
        return dao.delete(id);
    }

    @Override
    public boolean save(Skill skill) {
        final Integer skillId = skill.getId();
        if (skillId == null || skillId < 1) {
            boolean result = dao.insert(skill);
            System.out.println(skill.getId());
            return result;
        }
        return dao.update(skill);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Skill get(Integer id) {
        return dao.get(id);
    }

    @Transactional(readonly = true)
    @Override
    public List list() {
        return dao.list();
    }
}

controller:


@Controller
@RequestMapping("/skill")
public class SkillController {
    @Autowired
    private SkillService service;

    @PostMapping("/remove")
    @ResponseBody
    public String remove(Integer id) {
        return service.remove(id) ? "删除成功" : "删除失败";
    }

    @PostMapping("/save")
    @ResponseBody
    public String save(Skill skill) {
        return service.save(skill) ? "保存成功" : "保存失败";
    }

    @GetMapping("/get")
    @ResponseBody
    public Skill get(Integer id) {
        return service.get(id);
    }

    @GetMapping("/list")
    @ResponseBody
    public List list() {
        return service.list();
    }

}
纯注解—配置静态资源

@ComponentScan("programmer.lp.controller")
@EnableWebMvc
public class SpringMVCConfiguration implements WebMvcConfigurer {
    
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}
纯注解—配置拦截器

拦截器:

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}

XML配置:


    
         
纯注解—Converter 

Converter:

public class DateConverter implements Converter {
    private Set formats;
    public void setFormats(Set formats) {
        this.formats = formats;
    }
    @Override
    public Date convert(String dateStr) {
        if (null == formats || formats.isEmpty()) return null;
        for (String format : formats) {
            try {
                return new SimpleDateFormat(format).parse(dateStr);
            } catch (Exception e) {
                System.out.println("不支持:<" + format + ">格式!");
            }
        }
        return null;
    }
}

XML配置:

    
        
            
                
                    
                        
                            yyyy-MM-dd
                            yyyy/MM/dd
                            yyyy年MM月dd日
                        
                    
                
            
        
    
    

注解配置:

由于该DateConverter有可能不止SpringMVC会用到,因此将其放到SpringConfiguration中:

// ...
public class SpringConfiguration {
	// ...
    @Bean
    public DateConverter dateConverter() {
        DateConverter dateConverter = new DateConverter();
        Set set = new linkedHashSet<>();
        set.add("yyyy-MM-dd");
        set.add("yyyy/MM/dd");
        set.add("yyyy年MM月dd日");
        dateConverter.setFormats(set);
        return dateConverter;
    }
}
@ComponentScan("programmer.lp.controller")
//@ComponentScan({"programmer.lp.controller", "programmer.lp.interceptor"})
@EnableWebMvc
public class SpringMVCConfiguration implements WebMvcConfigurer {
    @Autowired
    private DateConverter dateConverter;

    @Override
    public void addFormatters(FormatterRegistry registry) {
    	// 注意:使用registry.addConverter(dateConverter);这种方式,同一个类型的Converter只能配置一个
        registry.addConverter(dateConverter);
    }
}
纯注解—MultipartResolver

不要忘记添加依赖,pom.xml:

    
        commons-fileupload
        commons-fileupload
        1.4
    

XML配置:

	
	    
	    
	

注解配置:

@ComponentScan("programmer.lp.controller")
@EnableWebMvc
public class SpringMVCConfiguration implements WebMvcConfigurer {
    @Bean
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        resolver.setDefaultEncoding("UTF-8");
        return resolver;
    }
}
纯注解—Initializer的本质

Initializer取代web.xml—直接实现WebApplicationInitializer

public class WebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // 父容器配置
        AnnotationConfigWebApplicationContext springCtx =
                new AnnotationConfigWebApplicationContext();
        springCtx.register(SpringConfiguration.class);
        // 通过监听器加载配置信息
        servletContext.addListener(new ContextLoaderListener(springCtx));

        // 子容器配置
        AnnotationConfigWebApplicationContext mvcCtx =
                new AnnotationConfigWebApplicationContext();
        mvcCtx.register(SpringMVCConfiguration.class);
        ServletRegistration.Dynamic servlet = servletContext.addServlet(
                "DispatcherServlet",
                new DispatcherServlet(mvcCtx));
        servlet.setLoadOnStartup(0);
        servlet.addMapping("/");

        // filter(解决POST请求乱码)
        FilterRegistration.Dynamic encodingFilter = servletContext.addFilter(
                "CharacterEncodingFilter",
                new CharacterEncodingFilter("UTF-8"));
        encodingFilter.addMappingForUrlPatterns
                (null, false, "/*");
    }
}
参考

小码哥-李明杰: Java从0到架构师③进阶互联网架构师.


本文完,感谢您的关注支持!


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5717139.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-18
下一篇2022-12-18

发表评论

登录后才能评论

评论列表(0条)

    保存