国王陛下万万岁

导航

 

要想让@Value注解获得properties文件当中的值,第一步需要Spring容器加载properties文件。

这就需要在配置类里面使用@PropertySoource注解来知道properties文件的路径了。

配置类代码:

package com.oxygen.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@ComponentScan({"com.oxygen.dao","com.oxygen.service"})
@PropertySource("jdbc.properties")
public class SpringConfig {
}

 

此时@Value注解的写法是:

@Value("${jdbc.mysql.password}")
private String password;

 

示例代码:

package com.oxygen.service.impl;

import com.oxygen.dao.BookDao;
import com.oxygen.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class BookServiceImpl implements BookService {

    @Value("2011000991")
    private int bookSN;

    @Value("${jdbc.mysql.password}")
    private String password;

    //注意:没有setter方法Autowired也能自动装配
    @Autowired
    @Qualifier("bookDao")
    private BookDao bookDao;

    public void save() {
        System.out.println("Book Service save...");
        System.out.println("Book SN:"+bookSN);
        System.out.println("数据库密码:"+password);
        bookDao.save();
    }
}

 

@PropertySource注解的不能使用星号(*)作为properties文件的通配符,因为没有任何文件可以用星号作为文件名。

多个properties文件要用数组各种,中间用逗号隔开。

@PropertySource可以加classpath:

@Configuration
@ComponentScan({"com.oxygen.dao","com.oxygen.service"})
@PropertySource("classpath:jdbc.properties")
public class SpringConfig {
}

  

posted on 2022-10-23 02:21  国王陛下万万岁  阅读(40)  评论(0编辑  收藏  举报