ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

SpringBoot常用配置(持续更新)

2021-11-24 21:30:50  阅读:130  来源: 互联网

标签:常用 return SpringBoot boot 更新 class initParameters new public


自动装配原理

  1. SpringBoot启动会加载大量的自动配置类xxxAutoConfiguration
  2. xxxAutoConfiguration会使用@EnableConfigurationProperties注解绑定配置文件中的属性值
  3. 给容器中的自动配置类添加组件时,会从xxxProperties类中获取指定的属性值,只需要在配置文件中指定这些属性即可.
  4. 配置文件中的key和xxxProperties中@ConfigurationProperties注解的prefix属性值一一对应

pom.xml

  • spring-boot-dependencies :核心依赖在父工程中

启动器starter :Springboot的启动场景

  • <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>2.3.7.RELEASE</version>
    </dependency>
    
  • 比如spring-boot-starter-web,会自动导入web环境所有的依赖

  • springboot会将所有的功能场景,都变成一个个的启动器

  • 要使用什么功能,就找到对应的启动器 starter


springboot的配置文件 application.yaml

通过查看原码(ResourceProperties类)
静态资源默认访问地址

  • classpath:/META-INF/resources/
  • classpath:/resources/
  • classpath:/static/
  • classpath:/public/

连接数据库,配置数据源

pom.xml引入相关依赖

  <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.27</version>
  </dependency>
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
  </dependency>

application.yaml

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

测试

@SpringBootTest
class SpringbootTestApplicationTests {
    @Autowired
    DataSource dataSource;
    @Test
    void contextLoads() throws SQLException {
        System.out.println(dataSource.getClass());
        System.out.println(dataSource.getConnection());
    }
}

整合mybatis

pom.xml引入相关依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>

application.yaml

mybatis:
  type-aliases-package: com.hyj.pojo
  mapper-locations: classpath:mybatis/mapper/*.xml

Dao层使用Mapper注解,并DI注入到容器

@Mapper
@Repository
public interface UserMapper {
    public User queryById(@Param("id") int id);
}

Service层调用Dao层,并DI注入到容器

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Override
    public User queryById(int id) {
        return userMapper.queryById(id);
    }
}

mapper-locations:的文件夹下创建相对应xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hyj.mapper.UserMapper">
    <select id="queryById" parameterType="int" resultType="user">
        select * from mybatis.user where id = #{id};
    </select>
</mapper>

测试

@SpringBootTest
class SpringbootTestApplicationTests {
    @Autowired
    private UserService userService;
    @Test
    void contextLoads() {
        System.out.println(userService.queryById(1));
    }
}

Druid 监控

@Configuration
public class DruidConfig {
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }
    //后台监控: web.xml
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        HashMap<String, String> initParameters = new HashMap<>();
        //增加配置
        initParameters.put("loginUsername","admin");  //登录key 固定 loginUsername loginPassword
        initParameters.put("loginPassword","123456");	
        //允许谁可以访问
        //initParameters.put("allow","127.0.0.2");
        //禁止谁访问 禁止ip访问
//        initParameters.put("deny","127.0.0.1");
        bean.setInitParameters(initParameters);
        return bean;
    }

    //filter
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
     bean.setFilter(new WebStatFilter());
        HashMap<String, String> initParameters = new HashMap<>();
        //这些东西不进行统计
        initParameters.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParameters);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}

配置完成后访问工程路径/druid,通过设置好的账号密码登录后台监控页面


自定义WebMvcConfigurer

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    public static class MyViewResolver implements ViewResolver {
        @Override
        public View resolveViewName(String s, Locale locale) throws Exception {
            return null;
        }
    }
    //自定义视图解析器
    @Bean
    public ViewResolver MyViewResolver(){
        return new MyViewResolver();
    }
    //自定义国际化相关
    @Bean
    public LocaleResolver localeResolver() {
        return new MyLocaleResolver();
    }
    //添加拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/login","/css/**","/img/**");
    }
}

国际化

在这里插入图片描述
自定义LocaleResolver类

public class MyLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String lang = httpServletRequest.getParameter("lang");
        Locale aDefault = Locale.getDefault();
        if(lang!=null && !("".equals(lang))) {
            String[] s = lang.split("_");
            aDefault = new Locale(s[0],s[1]);
        }
        return aDefault;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}

html层中英文切换传参

<a th:href="@{/login(lang='zh_CN')}">中文</a>
<a th:href="@{/login(lang='en_US')}">英文</a>

添加到自定义的WebMvcConfigurer

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Bean
    public LocaleResolver localeResolver() {
        return new MyLocaleResolver();
    }
}

标签:常用,return,SpringBoot,boot,更新,class,initParameters,new,public
来源: https://blog.csdn.net/HHeyanjie/article/details/121524653

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有