admin管理员组

文章数量:1794759

Spring Boot的常用注解(超细致)

Spring Boot的常用注解(超细致)

目录

Spring Boot

1.1 JavaConfig

1.2 @ImporResource

1.3 @PropertyResource


Spring Boot
  • 为什么要使用 Spring Boot

    因为Spring, SpringMVC 需要使用的大量的配置文件 (xml文件)

    还需要配置各种对象,把使用的对象放入到spring容器中才能使用对象

    需要了解其他框架配置规则。

  • SpringBoot 就相当于 不需要配置文件的Spring+SpringMVC。 常用的框架和第三方库都已经配置好了。

    拿来就可以使用了。

  • SpringBoot开发效率高,使用方便多了

  • 1.1 JavaConfig

    JavaConfig: 使用java类作为xml配置文件的替代, 是配置spring容器的纯java的方式。 在这个java类这可以创建java对象,把对象放入spring容器中(注入到容器),

    使用两个注解:

    1)@Configuration : 放在一个类的上面,表示这个类是作为配置文件使用的。

    2)@Bean:声明对象,把对象注入到容器中。

     测试

     

    例子: package com.bjpowernode.config; import com.bjpowernode.vo.Student; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Configuration:表示当前类是作为配置文件使用的。 就是用来配置容器的 * 位置:在类的上面 * * SpringConfig这个类就相当于beans.xml */ @Configuration public class SpringConfig { /** * 创建方法,方法的返回值是对象。 在方法的上面加入@Bean * 方法的返回值对象就注入到容器中。 * * @Bean: 把对象注入到spring容器中。 作用相当于<bean> * * 位置:方法的上面 * * 说明:@Bean,不指定对象的名称,默认是方法名是 id * */ @Bean public Student createStudent(){ Student s1 = new Student(); s1.setName("张三"); s1.setAge(26); s1.setSex("男"); return s1; } /*** * 指定对象在容器中的名称(指定<bean>的id属性) * @Bean的name属性,指定对象的名称(id) */ @Bean(name = "lisiStudent") public Student makeStudent(){ Student s2 = new Student(); s2.setName("李四"); s2.setAge(22); s2.setSex("男"); return s2; } } 1.2 @ImporResource

    @ImportResource 作用导入其他的xml配置文件, 等于 在xml

    <import resources="其他配置文件"/>

     写一个配置文件,声明。这里的声明是放在配置文件中的。根据猫的属性进行赋值。

    接下来我们借助@Configuration,加一个InportResource()

     导入到容器中;

     { }的话就可以指定多个配置文件

     如:

    @Configuration @ImportResource(value ={ "classpath:applicationContext.xml","classpath:beans.xml"}) public class SpringConfig { } 1.3 @PropertyResource

    @PropertyResource: 读取properties属性配置文件。 使用属性配置文件可以实现外部化配置 ,

    在程序代码之外提供数据。

     

    但是我们要把老虎对象放到指定的对象区域里去。

     测试:

    步骤:

  • 在resources目录下,创建properties文件, 使用k=v的格式提供数据

  • 在PropertyResource 指定properties文件的位置

  • 使用@Value(value="${key}")

  • @Configuration @ImportResource(value ={ "classpath:applicationContext.xml","classpath:beans.xml"}) @PropertySource(value = "classpath:config.properties") @ComponentScan(basePackages = "com.bjpowernode.vo") public class SpringConfig { }

     第一行是读和使用配置文件;第二行是扫描器;第三行导入配置文件

     所以类就相当于xml配置文件。

    本文标签: 注解细致常用springboot