Springboot学习笔记

目录

一、Hello Spring boot

1.1pom包

1.2启动类

1.3Controller层

二、连接数据库(方法一)

2.1pom包

2.2配置类

2.3配置文件

3.3Controller层

三、连接数据库(方法二,相对简洁)

3.1配置类

        3.2配置文件

四、连接数据库(方法三)

 4.1JdbcProperties

4.2JdbcConfig

五、配置多个yml文件

5.1yml文件

 5.2Controller层:

六、用lombok插件获取get,set和toString方法

6.1安装插件

6.2导入pom坐标

6.3实体类

七、设置拦截器

八、查询操作

8.1配置文件

8.2pojo

8.3Mapper

8.4Service 

8.5Controller

8.6启动类

九、单元测试


一、Hello Spring boot

1.1pom包

  <properties>
        <java.version>1.8</java.version>
    </properties>
    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.1.5.RELEASE</version>
    </parent>
    <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    </dependencies>

1.2启动类

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

1.3Controller层

@RestController
public class HelloController {
    @GetMapping("hello")
    public String hello(){
        return "hello spring boot";
    }
}

二、连接数据库(方法一)

2.1pom包

在一的pom包中增添如下内容:

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.6</version>
    </dependency>

2.2配置类

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test
jdbc.username=root
jdbc.password=xxxxxx

2.3配置文件

@Configuration //声明是配置类
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {
    @Value("${jdbc.url}")
    String url;
    @Value("${jdbc.driverClassName}")
    String driverClassName;
    @Value("${jdbc.username}")
    String username;
    @Value("${jdbc.password}")
    String password;
    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}

3.3Controller层

@RestController
public class HelloController {
    @Autowired
    private DataSource dataSource;
    @GetMapping("hello")
    public String hello(){
        System.out.println("dataSource"+dataSource);
        return "hello spring boot";
    }
}

三、连接数据库(方法二,相对简洁)

3.1配置类

3.2配置文件

@Configuration //声明是配置类
public class JdbcConfig {
    @Bean
    @ConfigurationProperties(prefix = "jdbc")
    public DataSource dataSource(){
          return new DruidDataSource();
    }
}

 四、连接数据库(方法三)

 4.1JdbcProperties

@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {
    private String url;
    private String driverClassName;
    private String username;
    private String password;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

4.2JdbcConfig

@Configuration //声明是配置类
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig {

    @Bean
    public DataSource dataSource(JdbcProperties jdbc){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(jdbc.getDriverClassName());
        dataSource.setUrl(jdbc.getUrl());
        dataSource.setUsername(jdbc.getUsername());
        dataSource.setPassword(jdbc.getPassword());
        return dataSource;
    }
}

五、配置多个yml文件

5.1yml文件

 

 5.2Controller层:

@RestController
public class HelloController {

    @Value("${duobaoyu.url}")
    private String yuUrl;
    @Value("${zhashutiao.url}")
    private String shutiaoUrl;
    @GetMapping("hello")

     public String hello(){
        System.out.println("duobaoyuurl="+yuUrl);
        System.out.println("shutiaourl="+shutiaoUrl);
        return "hello spring boot";
     }
}

六、用lombok插件获取get,set和toString方法

6.1安装插件

6.2导入pom坐标

       <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

6.3实体类

@Data
public class User {
    private Long id;
    // 用户名
    private String userName;
    // 密码
    private String password;
    // 姓名
    private String name;
    // 年龄
    private Integer age;
    // 性别,1男性,2女性
    private Integer sex;
    // 出生日期
    private Date birthday;
    // 创建时间
    private Date created;
    // 更新时间
    private Date updated;
    // 备注
    private String note;
    // getter和setter省略
}

加了@Data注解,实体类就无需添加get,set和toString方法,用的时候lombox插件会自动生成。

七、设置拦截器

@Slf4j
public class MyInterceptor implements HandlerInterceptor  {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("这是MyInterceptor拦截器的preHandle方法");
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.debug("这是MyIntercepor拦截器的postHandle方法");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.debug("这是MyIntercepor拦截器的afterCompletion方法");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
@Configuration
public class MvcConfig implements WebMvcConfigurer {

    /*
    将拦截器注册到Spirng ioc容器里
     */
    @Bean
    public MyInterceptor myInterceptor(){
        return new MyInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(myInterceptor()).addPathPatterns("/*");
    }
}

yml:

logging:
  level:
    com.bukaedu: debug
    org.springframework: info

八、查询操作

8.1配置文件

application.properties:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test
jdbc.username=root
jdbc.password=xxxxxx

application.yml:

spring:
  profiles:
    active: abc,def
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test
    username: root
    password: xxxxxx
  redis:
    host: localhost
    port: 6379

server:
  port: 80
logging:
  level:
    com.bukaedu: debug
    org.springframework: info
mybatis:
  type-aliases-package: com.bukaedu.pojo
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

8.2pojo

@Data
@Table(name="tb_user")
public class User {
    @Id
    @KeySql(useGeneratedKeys = true)
    private Long id;
    // 用户名
    private String userName;
    // 密码
    private String password;
    // 姓名
    private String name;
    // 年龄
    private Integer age;
    // 性别,1男性,2女性
    private Integer sex;
    // 出生日期
    private Date birthday;
    // 创建时间
    private Date created;
    // 更新时间
    private Date updated;
    // 备注
    private String note;
    // getter和setter省略
}

8.3Mapper

public interface UserMapper extends Mapper<User> {
}

8.4Service 

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    public User queryById(Long id){
        return userMapper.selectByPrimaryKey(id);

    }
    @Transactional
    public void savaUser(User user){
        userMapper.insertSelective(user);
        System.out.println("新增用户");
    }
}

8.5Controller

@RestController
public class HelloController {

   @Autowired
   private UserService userService;

   @GetMapping("/user/{id}")
     public User hello(@PathVariable Long id){
       return userService.queryById(id);
     }
}

8.6启动类

@SpringBootApplication
@MapperScan("com.bukaedu.mapper")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

九、单元测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserTest {
    @Autowired
    private UserService userService;
    @Test
    public void queryById(){
        User user=userService.queryById(1L);
        System.out.println("user="+user);
    }
    @Test
    public void saveUser(){
        User user=new User();
        user.setUserName("test");
        userService.savaUser(user);
    }
}

springboot学习笔记 spring基础 Spring概述 Spring的简史 xml配置 注解配置 java配置 Spring概述 Spring的模块 核心容器CoreContainer Spring-Core Spring-Beans Spring-Context Spring-Context-Support Spring-Expression AOP Spring-AOP Spring-Aspects Messaging Spring-Messaging WEB Spring-Web Spring-Webmvc Spring-WebSocket Spring-Webmvc-Portlet 数据访问/集成(DataAccess/Intefration) Spring-JDBC Spring-TX Spring-ORM Spring-OXM Spring-JMS Spring的生态 Spring Boot Spring XD Spring Cloud Spring Data Spring Integration Spring Batch Spring Security Spring HATEOAS Spring Social Spring AMQP Spring Mobile Spring for Android Spring Web Flow Spring Web Services Spring LDAP Spring Session Spring项目快速搭建 Maven简介 Maven安装 Maven的pom.xml dependencies dependency 变量定义 编译插件 Spring项目的搭建 Spring Tool Suite https://spring.io/tools/sts/all IntelliJ IDEA NetBeans https://netbeans.org/downloads/ Spring基础配置 依赖注入 声明Bean的注解 @Component组件,没有明确的角色 @Service在业务逻辑层(service层) @Repository在数据访问层(dao层) @Controller在展现层(MVC→SpringMVC) 注入Bean的注解 @Autowired:Spring提供的注解 @Inject:JSR-330提供的注解 @Resource:JSR-250提供的注解 Java配置 @Configuration声明当前类是一个配置类 @Bean注解在方法上,声明当前方法的返回值为一个Bean AOP @Aspect 声明是一个切面 拦截规则@After @Before @Around PointCut JoinPoint Spring常用配置 Bean的Scope Singleton Prototype Request Session GlobalSession SpringEL和资源调用 注入普通字符 注入操作系统属性 注入表达式云算结果 注入其他Bean的属性 注入文件内容 注入网址内容 注入属性文件 Bean的初始化和销毁 Java配置方式 注解方式 Profile @Profile 通过设定jvm的spring.profiles.active参数 web项目设置在Servlet的context parameter中 事件Application Event 自定义事件,集成ApplicationEvent 定义事件监听器,实现ApplicationListener 使用容器发布事件 Spring高级话题 Spring Aware BeanNameAware BeanFactoryAware
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值