springboot学习

1。javaConfig,使用java类代替xml配置文件使用,是配置spring容器的纯java方式

使用的两个注解

@Configuration 放在类上

@Bean 放在方法上 ,这个注解里面不配置name,那么这个方法名就是bean的id

@ImportResource,导入其他的xml配置文件,等价于

        <import resource="其他配置文件">
@Configuration
@ImportResource(value = "classpath:application.xml")
public class SpringConfig {
    @Bean
    public Student getStudent(){
        Student student = new Student();
        student.setAge(20);
        student.setName("李四");
        student.setSex("男");
        return student;
    }
}

@PropertySource,读取外部配置文件,使用配置文件可以实现外部化配置,在程序代码之外提供数据, 在resources目录下创建properties文件 k=v的格式

在PropertySource指定property文件的位置,使用@Value(“${key}”)注解给属性赋值

设置property文件需要注意把idea的编码格式设置为utf-8  ,设置方法  FILE—>SETTING—>查找encoding,全部设置为utf-8

配置类   ,因为Configuration替换了xml,而下面的三个注解都是在xml的替换方式,

@Configuration
@ImportResource(value = "classpath:application.xml")
@PropertySource(value = "classpath:config.properties")
@ComponentScan(basePackages = "com.abc.vo")
public class SpringConfig {

老虎类

@Component("tiger")
public class Tiger {
    @Value("${tiger.name}")
    private String name;
    @Value("${tiger.age}")
    private Integer age;

测试类

ApplicationContext ct = new AnnotationConfigApplicationContext(SpringConfig.class);
Tiger tiger = (Tiger) ct.getBean("tiger");
System.out.println(tiger);

@SpringBootApplication 是一个符合注解

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan

@SpringBootConfiguration,使用了这个注解标注的类是一个Configuration类,可以使用@Bean声明对象,注入容器中

@Configuration
@Indexed
public @interface SpringBootConfiguration {
    @AliasFor(
        annotation = Configuration.class
    )
    boolean proxyBeanMethods() default true;
}

@EnableAutoConfiguration,启用自动配置,把java对象配置好,放入到容器中,例如,把mybatis的对象创建好,放到容器中

@ComponentScan,扫描器,找到注解,根据注解的功能创建对象,给属性赋值,默认扫描的包,@ComponentScan所在的类所在的包和子包

springboot的配置文件

文件名  application      properties格式

server.port=8082
server.servlet.context-path=/myboot

yml格式

server:
  port: 8083
  servlet:
    context-path: /myboot2

多环境配置

创建多个配置文件,文件名称为  application-环境名称.properties或者.yml

如开发环境  application-dev.yml   测试环境  application-test.yml

spring.profiles.active=dev,这个就是配置使用application-dev.yml

@Value的使用 

@Value(“${key}”),  key来自于application.yml文件

school:
  name: 大学校
  add: 123
@Value("${school.name}")
private String name;

@Value("${school.add}")
private String add;

@ConfigurationProperties  给对象的属性赋值,在使用这个时会有提示,需要加上下面的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
@Component   //这里把对象加入到容器后,在其他地方就可以把这个对象注入使用了
@ConfigurationProperties(prefix = "school")
public class School {
    private String name;
    private String add;  加上get和set方法

使用容器

使用代码从容器中获取对象,可以使用run方法的返回值

public static void main(String[] args) {
    ConfigurableApplicationContext ctx = SpringApplication.run(DuohuanjingApplication.class, args);
    UserService u = (UserService) ctx.getBean("userService");
    u.f1();

ConfigurableApplicationContext 是ApplicationContext的子接口,这里一般在开发过程中自己测试时使用

CommandLineRunner接口和ApplicationRunner接口

这两个接口都有一个run方法, 执行时间在容器对象创建好后,自动执行run()方法,可以完成自定义的在容器对象创建好后的一些操作

@SpringBootApplication
public class DuohuanjingApplication implements CommandLineRunner {
@Resource
private UserService userService;

    public static void main(String[] args) {
        System.out.println("容器对象创建之前");   第一输出
        ConfigurableApplicationContext ctx = SpringApplication.run(DuohuanjingApplication.class, args);
        System.out.println("容器对象创建之后");   第三输出
        UserService u = (UserService) ctx.getBean("userService");
        u.f1();

    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("这里是main方法的run执行之后接着执行的");  第二输出
       这里可以在上面的主类里注入bean,然后这里直接调用bean的方法
        userService.say();
    }
}

拦截器

拦截器是springmvc的一种对象,能拦截对controller的请求,拦截器框架中有系统的拦截器,我们还可以自定义拦截器,完成对请求的预处理

自定义拦截器

  1. 定义一个类实现springmvc框架中的HandlerInterceptor接口

public interface HandlerInterceptor {
    default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;   //返回false则拦截
    }

    default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}

2.

 SpringBoot中使用拦截器的步骤

1.定义一个类实现springmvc框架中的HandlerInterceptor接口

public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("执行拦截器。。。");
        return true;
    }
}

2.定义一个配置类实现  WebMvcConfigurer接口,重写  addInterceptors方法

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        HandlerInterceptor interceptor = new MyInterceptor();
        String[] paths={"/usr/add"};   //要拦截的请求,controller中配置的
       //这里可以使用  /usr/**  表示 /usr 开始的请求都拦截
        String[] exclupath={"/usr/login"};  //放行的请求不拦截,controller中配置的
         registry.addInterceptor(interceptor).addPathPatterns(paths).excludePathPatterns(exclupath);
    }
}

springboot中使用Servlet步骤

1  定义一个类继承HttpServlet

public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println("执行了Servlet");
        out.flush();
        out.close();
    }

2.定义一个配置类注册servlet,通过ServletRegistrationBean注册bean

@Configuration
public class ServletConfig {

    @Bean
    public ServletRegistrationBean getServletRegistrationBean(){
        ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.setServlet(new MyServlet());
        Collection<String> c = new ArrayList<>();
        c.add("/myservlet"); //访问这个地址会访问到servlet
        bean.setUrlMappings(c);
        return bean;
    }
}

或者使用下面这句

@Bean
public ServletRegistrationBean getServletRegistrationBean(){
    ServletRegistrationBean bean = new ServletRegistrationBean();
    bean.setServlet(new MyServlet());
    Collection<String> c = new ArrayList<>();
    c.add("/myservlet");
    c.add("/yourservlet");
    bean.setUrlMappings(c);
    return bean;

springboot中使用Filter过滤器步骤

1.定义一个类实现Filter接口

public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器执行了");
        filterChain.doFilter(servletRequest,servletResponse);
    }
}

2.注册Filter对象

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean filterRegistrationBean(){
        FilterRegistrationBean fbean = new FilterRegistrationBean();
        fbean.setFilter(new MyFilter());
        fbean.addUrlPatterns("/usr/*");   //这里只能写单个的*号
        return fbean;
    }
}

字符集过滤器

CharacterEncodingFilter,这个是框架已经写好的过滤器, 我们只需要自己把这个过滤器配置到程序中,直接使用就可以了。

1.在配置类中注册字符集过滤器

@Bean
public FilterRegistrationBean filterRegistrationBean2(){
    FilterRegistrationBean bean = new FilterRegistrationBean();
    CharacterEncodingFilter filter = new CharacterEncodingFilter();
    filter.setEncoding("utf-8");
    filter.setForceEncoding(true);
    bean.setFilter(filter);
    bean.addUrlPatterns("/*");
    return bean;
}

2.application.yml 文件里面修改springboot的默认配置,默认配置是ISO-8859-1,默认server.servlet.encoding.enabled=true,启用了springboot默认的配置,这里我们把true改为false,启用我们自己配置的字符集过滤器

server:
  servlet:
    encoding:
      enabled: false

实际开发中,我们不需要自己去注册CharacterEncodingFilter类,因为springboot已经给我们注册好了,我们只需要去配置这个类的属性即可。配置信息如下

server:
  servlet:
    encoding:
      enabled: true
      charset: utf-8
      force: true

 关于mapper注解的使用,

第一种方式

@Mapper,放在mapper接口上面,每一个mapper都需要加上这个注解

@Mapper   //告诉mybatis这是dao接口,需要创建接口的代理对象
public interface UserMapper {
    public User selectById(@Param("id") Integer id);
}

第二种方式,在主启动类上加上  @MapperScan注解,扫描mapper接口所在的包

spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8

如果实际开发中,mapper接口和mapper.xml文件不在同一个包中,可以通过一下设置

1.在resources目录下建立  mapper文件夹,将所有的mapper.xml文件都放到mapper文件夹中,

2.在application.yml中配置  mapper.xml文件的路径

mybatis.mapper-locations=classpath:mapper/*.xml

配置mybatis的日志

mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

3.在pom.xml文件配置插件

<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
    </resource>
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>**/*.xml</include>
            <include>**/*.properties</include>
        </includes>
    </resource>
</resources>

事务

spring框架中的事务

管理事务的对象,事务管理器(是个接口,有很多的实现类)

例如,使用jdbc或者mybatis访问数据库,使用的事务管理器是DataSourceTransactionManager

声明式事务  通过配置文件或者注解说明事务控制的内容

隔离级别,传播行为,超时时间

事务处理方式

1。 Spring框架中的  @Transactional  注解

2.  Aspectj 框架可以在xml中配置文件,声明事务控制的内容

Springboot使用事务

1,在方法上加入  @Transactional ,这个方法上就有事务功能了

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Transactional  //这个注解标注的方法如果抛出 运行时异常,该方法的事务就会回滚
    public int addUser(User user) {
        int rows =  userMapper.addUser(user);
    //    int i = 10/0;   //这里抛出运行时异常,这个方法的事务会回滚
        return rows;
    }
}

2,明确的在主启动类上,加上@EnableTransactioManager 注解,这个不是必须的,加上之后比较明显

@SpringBootApplication
@EnableTransactionManagement
@MapperScan(basePackages = "com.example.springbootmybatistransaction.mapper")
public class SpringbootMybatisTransactionApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisTransactionApplication.class, args);
    }
}
<mapper namespace="com.example.springbootmybatistransaction.mapper.UserMapper">
    <insert id="addUser" >
        insert into user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id!=null and id>0">id,</if>
            <if test="name!=null and name!=''">name,</if>
            <if test="pwd!=null and pwd!=''">pwd,</if>
        </trim>
        <trim prefix="values(" suffixOverrides="," suffix=")">
            <if test="id!=null and id>0">#{id},</if>
            <if test="name!=null and name!=''">#{name},</if>
            <if test="pwd!=null and pwd!=''">#{pwd},</if>
        </trim>
    </insert>
</mapper>

关于pom文件中的插件

  在pom文件中配置插件后,在IDEA的右侧maven功能里面的plugins里面就会显示该插件,双击该插件就可以是哟个

RESTFul接口架构风格

接口(API),可以指 访问 servlet或者controller中的url,或者调用其他程序的函数

架构风格:api的组织方式

就是一个传统的   http://localhost:8999/mytrans/addUser?id=1005&name=lisi&pwd=123  ,

在地址上提供了访问的资源名称 addUser,在其后使用了get方式传递参数

RESTful架构风格

通过请求方式,表示对资源的CRUD

GET:查询   POST:新增  PUT:修改  DELETE:删除

 @PathVariable 注解,从url中获取数据

@GetMapping("/queryUser/{upid}")  //upid就是接收地址栏中的数据的
public String queryUser(@PathVariable("upid") Integer id){ //将地址栏接收的数据映射到id这个变量中去,如果upid这个名字和id这个名字是一样的情况下,@PathVariable注解里面可以不用带参数
    User user = userService.getById(id);
    return user.toString();
}

@GetMapping("/addUser/{id}/{name}/{pwd}")
public String f1(@PathVariable("id") Integer id,@PathVariable String name,@PathVariable String pwd){
    User user = new User();
    user.setId(id);
    user.setName(name);
    user.setPwd(pwd);
    int rows = userService.addUser(user);
    return user.toString()+",成功,rows="+rows;
}

要使用put或者delete请求

spring.mvc.hiddenmethod.filter.enabled=true

使用   RESTful风格的请求,需要保证   请求方式+URI  是唯一的


版权声明:本文为weixin_44681177原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。