一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

idea将maven项目改成Spring boot项目方法代码示例

时间:2020-09-07 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下idea将maven项目改成Spring boot项目方法代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

1、添加parent父级依赖

在pom.xml文件中,要首先添加parent父级依赖



  org.springframework.boot
  spring-boot-starter-parent
  2.2.4.RELEASE
   


2、添加spring-boot-starter核心依赖和测试依赖

在dependencies中,添加spring-boot-starter核心依赖,并添加核心测试依赖


  
  
    org.springframework.boot
    spring-boot-starter
  
  
  
    org.springframework.boot
    spring-boot-starter-test
    test
    
      
        org.junit.vintage
        junit-vintage-engine
      
    
  

3、添加properties属性配置

properties属性配置主要是存放依赖的版本号,可以自定义,相对于定义了一个变量


  
  1.8
  
  1.1.17



  
  
    com.alibaba
    druid-spring-boot-starter
    
    ${druid.version}
  

4、添加build打包插件配置



  
    
      org.springframework.boot
      spring-boot-maven-plugin
    
  


5、搭建入口类

Spring boot项S目一般都有一个*Application.java的入口类,里面有一个main的方法,这是标准Java应用程序的入口方法。

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

在main方法中执行的Spring Application的run方法,返回一个上下文的容器实例

public static void main(String[] args) {
  //SpringApplication的run方法返回一个上下文的容器实例
  ApplicationContext context = SpringApplication.run(TestApplication.class, args);
  //从容器获取bean对象
  UserService service = context.getBean(UserServiceImpl.class);
  service.say();
}

@SpringBootApplication注解是Spring boot的核心注解,它是一个组合注解,主要包含以下注解:

1、@SpringBootConfiguration:这是Spring boot项目的配置注解,这也是一个组合注解

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
  @AliasFor(
    annotation = Configuration.class
  )
  boolean proxyBeanMethods() default true;
}

2、@EnableAutoConfiguration:启用自动配置,该注解会使Spring boot根据项目中依赖的jar包自动配置项目的配置项

3、@ComponentScan:默认扫描@SpringBootApplication所在类的同级目录以及它的子目录。

如果Spring boot项目中整合了SpringMVC,那么就需要添加一个注解@MapperScan,这个注解的作用是告诉容器dao包中的接口的路径,使得可以在运行时动态代理生成实现类并放入到容器中管理。

@SpringbootApplication
@MapperScan({"edu.nf.ch01.user.dao", "edu.nf.ch01.product.dao"})
public class TestApplication(){
  public static void main(String[] args){
    SpringApplication.run(TestApplication.class, args);
  }
}

6、application配置文件

在resource目录中创建一个application.properties文件或者application.yml(推荐)文件,对项目的相关配置都可以在这个文件中配置。

7、搭建测试环境

在test目录下创建测试类,在类名上加@SpringBootTest注解,在测试类中还可以注入bean,Spring boot会完成自动注入。

@SpringBootTest
public class UsersTest(){
  
  @AutoWired
  private UserService service;
  
  @Test
  void testUser(){
    ...
  }
}

热门栏目