栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot笔记

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot笔记

springboot

1.springboot是快速开发框架。微服务:将一个应用程序拆分为一个个可独立运行的微服务,每个服务专注于做一件事。 2.第一个springboot程序

主程序

@SpringBootApplication//标记为这是一个springboot的应用
public class Springboot01HelloworldApplication {
​
    public static void main(String[] args) {
        SpringApplication.run(Springboot01HelloworldApplication.class, args);
    }
}

pom.xml依赖



    4.0.0
    //父依赖
    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.6
         
    
    //gav
    com.scholar
    springboot-01-helloworld
    0.0.1-SNAPSHOT
    springboot-01-helloworld
    springboot-01-helloworld
    
        1.8
    
    

        
            org.springframework.boot
            spring-boot-starter-web
        
//单元测试
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    
//插件
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

2.spring原理

 
            org.springframework.boot
            spring-boot-starter-web
 

spring-boot-starter就是启动器,想使用什么就导入什么。spring-boot-starter-web就是导入了web环境的所有依赖

3.springboot的理解

自动装配,run()方法

4.yml的使用

yaml可以替代peoperties。通过key:空格value来赋值

# 对象写法
student:
  name: lang
  age: 3
  #行内写法
  student: {name= lang,age: 3}
# 数组写法
pets:
  - cat
  - dog
  - bird
# 行内写法
  pets: [cat,dog,bird]
#可以通过debug= true来看哪些自动配置类生效了。哪些没生效

5.自动装配原理
//首先找到总的配置spring.factories,这个总的配置了spring的值。
//spring.factories里有不同的自动装配类,每个自动装配类@xxxautoConfiguration自动装配类,将这些类交给spring进行管理,每个自动装配类绑定一个@ConfigurationProperties(prefix = "xxx")对属性进行自定义赋值,当我们需要用到哪些属性时再application.yml对属性进行赋值。

6.静态资源加载
静态资源加载一般可以放在classpath(resource)下的static,public,resource中,其中优先级顺序是static>public>resource
7.首页加载
在静态资源下创建index.html,系统会默认访问这个页面为首页。如果出现乱码,添加
将乱码转换为utf-8。
8.页面跳转
如果需要进行页面跳转,springboot默认配置了视图解析器是在templates下的html页面,所以我们要跳转的页面必须放在templates下并且以html作为后缀名。如果要在页面接收参数,要通过th:text="${msg}来获取参数
9.thymeleaf前端语法



    //防止中文乱码
    Title





//foreach:将后端传的参数lang的值赋给user,然后将user输出到前端页面上
10.cookie的作用域
cookie作用域是在一个浏览器内生效(默认),可以自己设置存活时间
11.员工管理系统
11.1编写实体类,连接数据库

11.2首页配置:
         1静态资源配置要导入thymeleaf依赖
         2.路径用@{/}

11.3页面国际化:
         1.我们需要配置i8n(国际化英文的简写,首字母和尾字母中间有18)文件
         2.我们如果需要在项目中使用按钮自动切换,需要自定义一个组件localeResolver
         3.要将自己写的组件装配到spring容器中,用@bean
         4.页面用#{}
11.4登录和拦截器
11.5员工列表展示
         1.提取公共页面
                 1.
                 2.
                 3.如果要传递参数,可以直接使用()传参,接收判断即可
         2.列表循坏展示

12.springboot-mybatis整合
//接口类
//mapper相当于以前的扫描包
@Mapper
//将这个接口注册到myabtis里
@Repository
public interface UserMapper {
    List queryUser();
    User queryUserByid(int id);
    int addUser(User user);
    int updateUser(Map map);
    int deleteUser(int id);
}
//在resource下编写sql



   
   select * from user where id=#{id}


   insert into user(id,name,password) values (#{id},#{name},#{password})

   
      update user set name=#{name},password=#{password} where id=#{id}
   

   delete from user where id=#{id}


mybatis:
  type-aliases-package: com.scholar.pojo  //对实体类起别名

  mapper-locations: classpath:mybatis/mapper
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
       //授权
        http.authorizeRequests()
               .antMatchers("/").permitAll()
               .antMatchers("/level1/**").hasRole("vip1")
               .antMatchers("/level2/**").hasRole("vip2")
               .antMatchers("/level3/**").hasRole("vip3");
        //跳转到login
http.formLogin();
        //注销,然后放回到/下的页面
http.logout().logoutSuccessUrl("/");
        //记住我
http.rememberMe();
    }
    //认证

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("scholar").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");
    }
}
14.shiro
1.快速开始
​      1.1先导依赖(shiro-core,jcl-over-slf4j,log4j,slf4j-log4j)
       1.2编写shiro.xml
       1.3编写日志log4j.properties
       1.4编写实体类quickstart
15.shiro集成springboot

1.环境搭建,导入shiro-spring包

2.写配置类,UserRealm实现授权和认证,ShiroConfig实现shiro基本3大类

//创建realm对象
public class UserRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证");
        return null;
    }
}
@Configuration
public class ShiroConfig {
    //shirofilterfactorybean=====第三步
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("SecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //关联defaultWebSecurityManager
        bean.setSecurityManager(defaultWebSecurityManager);
        
        //拦截请求到login
         Map filterMap=new LinkedHashMap<>();
        //拦截user路径下的所有路径,authc表示认证了才能访问
        filterMap.put("/user/*","authc");
        bean.setFilterChainDefinitionMap(filterMap);
        //如果没有认证就跳转到/toLogin
        bean.setLoginUrl("/toLogin");
        
        return bean;
    }
    //defaultwebsecuritymanager==========第二步
    @Bean(name ="SecurityManager" )
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager SecurityManager = new DefaultWebSecurityManager();
        //关联userRealm
        SecurityManager.setRealm(userRealm);
        return SecurityManager;
    }
    //创建realm对象,需要自定义====第一步
    @Bean(name = "userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }
}

3.实现页面跳转和前端页面编写

@Controller
public class MyController {
    @RequestMapping("/")
    public String toIndex(Model model){
        model.addAttribute("msg","hello,shiro");
        return "index";
    }

    @RequestMapping("/user/add")
    public String add(){
        return "user/add";
    }
//跳转页面不需要加/,页面本身就在classpath下,路径要写/代表localhost:8080
    @RequestMapping("/user/update")
    public String update(){
        return "user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }
}

16.swagger

1.导包springfox-swagger2,springfox-swagger-ui

2.编写配置类

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    //创建多个docket可以创建多个角色
    @Bean
    public Docket docket1(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("A");
    }
    @Bean
    public Docket docket2(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("B");
    }
    @Bean
    public Docket docket3(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("C");
    }
    //一个docket就是一个角色
    @Bean
    public Docket docket(Environment environment){
//设置要显示swagger环境
        Profiles profiles = Profiles.of("dev", "test");
        //通过environment.acceptsProfiles来判断自己在哪个环境中,环境在properties里配置
        boolean flag = environment.acceptsProfiles(profiles);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
               //设置是否启动,如果是在开发中启动,发布时不启动,通过配置文件
            //设置默认配置为dev的spring.profiles.active=dev,然后在dev里修改端口号
             .enable(flag)
                .select()
                //RequestHandlerSelectors:配置要扫描接口的方式
                //basePackage指定扫描包
                .apis(RequestHandlerSelectors.basePackage("com.scholar.controller"))
                .build();
    }
    //修改默认信息
    private ApiInfo apiInfo(){
        //作者信息
        Contact contact = new Contact("scholar", "https://www.bilibili.com/", "6666@qq.com");
        return  new ApiInfo("scholar swagger",
                "牛哇",
                "1.0",
                "urn:tos",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList());
    }
}

3.实体类

//使用注解来进行注释
@ApiModel("用户实体类")
public class User {
    @ApiModelProperty("用户名")
    public  String username;
    @ApiModelProperty("密码")
    public  String password;
}

4.提供接口

@RestController
public class MyController {
    @RequestMapping("/swagger")
    public String swagger(){
        return "hello,swagger";
    }

    @PostMapping("/user")
    public User user(){
        return  new User();
    }
}

小结:swagger是调节前后端分离的工具,使用swagger只需要导入springfox-swagger2,springfox-swagger-ui,再在类上加@Configuration,@EnableSwagger2这两个注解就行.可以修改默认值和多个对象以及对复杂的类进行注释,方便前端使用。并且可以进行测试。

17.三大任务

1.异步任务

1.在方法上面加@aysnc
2.在主启动类上加@EnableAsync

2.邮件任务

先在配置文件中properties配置

spring.mail.username=1942682514@qq.com
//密码是smtp加密后的
spring.mail.password=dotwalllnyhzdbec
spring.mail.host=smtp.qq.com
#开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true

然后再测试类里(简单邮件发送)

@SpringBootTest
class TaskApplicationTests {
    @Autowired
    JavaMailSenderImpl mailSender;

    @Test
    void contextLoads() {
        SimpleMailMessage MailMessage = new SimpleMailMessage();
        MailMessage.setSubject("你好,scholar");
        MailMessage.setText("加油,你是最棒的");
        MailMessage.setTo("1942682514@qq.com");
        MailMessage.setFrom("1942682514@qq.com");
        //邮件发送信息
        mailSender.send(MailMessage);
    }

}

复杂邮件发送

   @Test
    void contextLoads2() throws MessagingException {
//创建一个复杂邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //组装
        MimeMessageHelper Helper = new MimeMessageHelper(mimeMessage, true);
        //发送标题
Helper.setSubject("你好,scholar");
//正文,带格式
Helper.setText("

"加油,你是最棒的"

",true); //附件 Helper.addAttachment("qq",new File("C:\Users\19426\Desktop\1.png")); //发送给谁 Helper.setTo("1942682514@qq.com"); //谁发送消息 Helper.setFrom("1942682514@qq.com"); //邮件发送信息 mailSender.send(mimeMessage); }

3.定时执行任务

3.1先在主启动类上加注解@EnableScheduling//开启定时执行注解,再类上加注解 @Scheduled//启动定时

3.2然后编写类

@Service
public class ScheduledService {
    //6个数分别代表秒,分,时,日,月,周几(周天表达为0或7),?代表是随便是周几  6#3代表每个月第三周礼拜五
    @Scheduled(cron = "0 * * * * ?")
    public void hello(){
        System.out.println("定时操作");
    }
}

3.3启动主启动类加载任务

18分布式以及RPC
18.1.分布式:指当一个计算机无法完成某个任务时,将这个任务交给某些计算机完成。这些计算机连接了同一网络,为了完成同一目标而运行,我们将这些计算机看作是一个计算机系统,通过nigax进行负载均衡。例如淘宝(多个计算机完成,但是用户看相当于同一计算机)

18.2:RPC类似于http协议,都是基于网络进行通信的。是远程通信协议。有两个最大的特点:通信和序列化
序列化:在两台计算机通信时,发送方将信息封装到文件中,序列化变成计算机能看懂得二进制代码,接收方将进行反序列化,读取文件。
18.3:dubbo是RPC框架,而RPC是是远程调用,帮助分布式调用计算机之间的联系。
18.4:zookeeper是分布式的,开放源码的分布式应用程序协调服务
19.idea注意事项
1.maven项目有父依赖,maven项目的依赖在父依赖导就行。
  springboot项目都是独立的,poml要单独导。
2.maven项目在父依赖导就行
依赖就是一些jar包,jar包就是将编写的类进行打包,项目中导入jar包就可以调用类的方法。
extreme lib里放的是本地仓库里的东西

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/839072.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号