美文网首页
spring boot 属性注入

spring boot 属性注入

作者: 思无邪_72a7 | 来源:发表于2020-03-24 11:42 被阅读0次

spring boot 属性注入

首先我们在spring boot项目里新建一个book类,添加属性和方


public class Book {
    
    private Long id;
    private String name;
    private String author;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", author='" + author + '\'' +
                '}';
    }
}

接下来在resources目录下新建一个boo.properties的文件,写入如下内容


book.name=三国演义
book.author=罗贯中
book.id=99

然后在book类下添加如下注解

@Component                                      //实例化
@PropertySource("classpath:book.properties")    //选择book.properties作为配置文件
public class Book {
    @Value("${book.id}")                       //设置id为book.id,也就是刚才配置文件写的内容
    private Long id;
    @Value("${book.name}")
    private String name;
    @Value("${book.author}")
    private String author;

上面这种方法是spring提供的,下面我们来看一看另一种Spring boot用法

@Component
@PropertySource("classpath:book.properties")
@ConfigurationProperties(prefix = "book")  //加上这个注解之后,就不用去写value注解了,更便捷
public class Book {
   // @Value("${book.id}")
    private Long id;
   // @Value("${book.name}")
    private String name;
    // @Value("${book.author}")
    private String author;

至此,我们的属性注入就已经完成了。

下面,用test类来测试一下

@RunWith(SpringRunner.class)
@SpringBootTest
class PropertiesApplicationTests {

    @Autowired
    Book book;

    @Test
    void contextLoads() {
        System.out.println(book);
    }

}

运行test类,最后打印

Book{id=99, name='三国演义', author='罗贯中'}

注意,这里面引用了junit,小伙伴们如果运行出错的话,可能就是没有引入junit。

博客地址:https://badogyang.club/archives/sprintboot属性注入

相关文章

网友评论

      本文标题:spring boot 属性注入

      本文链接:https://www.haomeiwen.com/subject/ljhoyhtx.html