在@Configuration类中使用application.properties,@ Bean方法现在可以使用

时间:2019-09-16 05:03:23

标签: java spring spring-boot

我在java springboot中具有以下配置类定义。但是,它无法引用属性值。

@org.springframework.context.annotation.Configuration
public class HbaseConfig {

@Value("${keytab.user.name}")
private String username;

@Value("${keytab.path}")
private String keytabpath;

@Bean
public Connection getHbaseConnect() throws IOException {
    Configuration conf = HBaseConfiguration.create();
    Connection connection = ConnectionFactory.createConnection(conf); 
    UserGroupInformation.setConfiguration(conf);

    System.out.println("hbase connect..is connection closed..." + connection.isClosed());
    UserGroupInformation.loginUserFromKeytabAndReturnUGI(username, keytabpath);
    return connection;
}

@Bean
public Admin getHbaseAdmin(Connection connection) throws IOException{
    Admin admin = connection.getAdmin();
    return admin;
}

}

application.properties

 keytab.user.name="username"
 keytab.path="pathtokeytab"

为简单起见,我需要从我的HbaseConfig类的属性文件中读取上述keytab用户名和路径。

3 个答案:

答案 0 :(得分:1)

可以请您尝试以下方法,

  @ConfigurationProperties(prefix = "keytab")
  public class KeyTabConfig {

        private String username;

        private String path;

        public String getUsername(){ return this.username; }
        public String getPath(){ return this.path;}
        }

Habseconfig类如下

@Configuration
@EnableConfigurationProperties({ KeyTabConfig.class})
public class HbaseConfig {

              @Bean
              public Connection getHbaseConnect(KeyTabConfig keyTabConfig) throws IOException {
                   Configuration conf = HBaseConfiguration.create();
                   Connection connection = 
                   ConnectionFactory.createConnection(conf); 
                   UserGroupInformation.setConfiguration(conf);

                   System.out.println("hbase connect..is connection closed..." + 
                   connection.isClosed());
                   UserGroupInformation.loginUserFromKeytabAndReturnUGI(keyTabConfig.getUsername(), keyTabConfig.getPath());
                   return connection;
                 }

             @Bean
             public Admin getHbaseAdmin(Connection connection) throws IOException{
               Admin admin = connection.getAdmin();
               return admin;
              }

          }

application.properties文件为

    keytab.username=uname
    keytab.path=path

答案 1 :(得分:0)

  1. 确保您的属性文件名称应为application.properties,位置应位于
  

src / main / resources / application.properties

  1. 在类级别仅使用@Configuration,还使用@PropertySource定义属性文件的位置。@PropertySource("classpath:configprops.properties")如果属性文件名不同。

否则,Spring使用默认位置(classpath:application.properties).

答案 2 :(得分:-1)

@Value批注的实际处理是由BeanPostProcessor执行的,因此我们不能在BeanPostProcessor类型中使用@Value。

示例:https://www.concretepage.com/spring-5/spring-value#placeholder

链接:How exactly does the Spring BeanPostProcessor work?