读 Spring Boot实战笔记--day007

接上一章:读 Spring Boot实战笔记–day006
声明式事务

@Transactional
public void savesomething(Long id,String name) {
//数据库操作
}

Spring 提供了一个@EnableTransactionManagement 注解在配置类上来开启声名式事务的支持。使用了@EnableTransactionManagement后,Spring 容器会自动扫描注解@Transactional

@configuration
@EnableTransactionManagement
public class AppConfig {
}

读 Spring Boot实战笔记--day007_第1张图片
读 Spring Boot实战笔记--day007_第2张图片
类级别使用@Transactional

@Transactional不仅可以注解在方法上,也可以注解在类上。当注解在类上的时候意味着此类的所有 public方法都是开启事务的。如果类级别和方法级别同时使用了@Transactional注解,则使用在类级别的注解会重载方法级别的注解。
①可以直接注入我们的RersonRepository 的Bean。
②使用@Transactional注解的rollbackFor属性,指定特定异常时,数据回滚,
③硬编码手动触发异常。
④使用@Transactional注解的noRollbackFor 属性,指定特定异常时,数据回滚。
读 Spring Boot实战笔记--day007_第3张图片
开启缓存

@Configuration
@EnableCaching
public class AppConfig[
}

Spring Security
安全框架有两个重要的概念,即认证(Authentication) 和授权(Authorization)。认证即确认用户可以访问当前系统;授权即确定用户在当前系统下所拥有的功能权限,本节将围绕认证和授权展开。
配置:
SpringSecurity的配置和SpringMVC的配置类似,只需在一个配置类上注解@EnableWebSecurity,并让这个类继承WebSecurityConfigurerAdapter 即可。我们可以通过重写configure方法来配置相关的安全配置。

<!--  引入数据源   -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.18</version>
</dependency>

yml 数据源配置:

# 数据源配置
# 数据源配置
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:oracle:thin:@192.168.0.433:1521/ROOT
package com.example.spring;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author: hyh
 * @Date: 2021/12/3 14:06
 **/
@Data
public class MyUser implements UserDetails {

    /**
     * userName
     */
    @Getter
    private String userName;

    /**
     * password
     */
    @Getter
    private String password;

    private List<Role> roles;


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> list = new ArrayList<>();
        List<Role> roles = this.getRoles();
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority(role.getName()));
        }
        return list;
    }

    @Override
    public String getPassword() {
        return this.userName;
    }

    @Override
    public String getUsername() {
        return this.password;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

package com.example.spring;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * @Author: hyh
 * @Date: 2021/12/3 13:59
 **/
public class MyUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws 
    UsernameNotFoundException {
        //写自己的验证逻辑,和数据库数据对比
        return new MyUser();
    }
}
package com.example.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.
AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.
WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

import javax.sql.DataSource;

/**
 * @Author: hyh
 * @Date: 2021/12/2 17:28
 **/
@Configuration
public class WebSecurityConf extends WebSecurityConfigurerAdapter {


    @Autowired
   private DataSource dataSource;

    @Bean
    public UserDetailsService myUserDetailsService() {
        return new MyUserDetailsService();
    }

    // 认证授权
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("hyh").password("123456")
        .roles("ADMIN");
        // 可以配置自己的数据源
        auth.jdbcAuthentication().dataSource(dataSource);
        //定义自己的 UserDetailsService
        auth.userDetailsService(myUserDetailsService());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()// 开启自己的登录设置
        .loginPage("/login") //登陆页面
                .defaultSuccessUrl("/index") // 登陆成功跳转的页面
                .failureUrl("/error") //登陆失败跳转的页面
                .permitAll()
                .and()
                .rememberMe() // 开启cookie 记住我
                .tokenValiditySeconds(60*60) //cookie过期时间 1小时
                .key("myKey") // cookie 中 私钥
                .and()
                .logout() // 退出定制
                .logoutUrl("/logout") //退出页面
                .logoutSuccessUrl("/logout-success") //推出成功跳转
                .permitAll();
    }

}

读 Spring Boot实战笔记--day007_第4张图片

你可能感兴趣的:(Spring,spring,boot,java,spring)