GVKun编程网logo

使用纯Java配置的Spring 3.2 @value注释不起作用,但是Environment.getProperty起作用

29

如果您对使用纯Java配置的Spring3.2@value注释不起作用,但是Environment.getProperty起作用感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解使用纯Java配置

如果您对使用纯Java配置的Spring 3.2 @value注释不起作用,但是Environment.getProperty起作用感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解使用纯Java配置的Spring 3.2 @value注释不起作用,但是Environment.getProperty起作用的各种细节,此外还有关于005-Spring Boot配置分析-配置文件application、Environment、PropertySource、@Value、EnvironmentPostProcessor、Pr...、@ManagedBean注释不起作用,但@Named起作用、Angular environment.ts问题JSON但是environment.prod.ts、env.getProperty不起作用Spring PropertyPlaceholderConfigurer的实用技巧。

本文目录一览:

使用纯Java配置的Spring 3.2 @value注释不起作用,但是Environment.getProperty起作用

使用纯Java配置的Spring 3.2 @value注释不起作用,但是Environment.getProperty起作用

我一直在为此努力。不知道我在想什么。我无法使@Value注释在纯Java配置的Spring应用程序(非Web)中工作

@Configuration@PropertySource("classpath:app.properties")public class Config {    @Value("${my.prop}")     String name;    @Autowired    Environment env;    @Bean(name = "myBean", initMethod = "print")    public MyBean getMyBean(){         MyBean myBean = new MyBean();         myBean.setName(name);         System.out.println(env.getProperty("my.prop"));         return myBean;    }}

该属性文件仅包含my.prop=avaluebean,如下所示:

public class MyBean {    String name;    public void print() {        System.out.println("Name: " + name);    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}

环境变量会正确打印该值,而@Value不会正确打印。

avalueName: ${my.prop}

主类只是初始化上下文。

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);

但是,如果我使用

@ImportResource("classpath:property-config.xml")

这个片段

<context:property-placeholder location="app.properties" />

然后就可以了 当然现在环境又回来了null

答案1

小编典典

在你的Config类中添加以下bean声明

@Beanpublic static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {    return new PropertySourcesPlaceholderConfigurer();}

为了使@Value注释生效,PropertySourcesPlaceholderConfigurer应该注册。它使用时自动完成<context:property-placeholder>的XML,但应注册为一个static @Bean使用时@Configuration

005-Spring Boot配置分析-配置文件application、Environment、PropertySource、@Value、EnvironmentPostProcessor、Pr...

005-Spring Boot配置分析-配置文件application、Environment、PropertySource、@Value、EnvironmentPostProcessor、Pr...

一、配置文件application

  springboot配置文件,默认配置文件application.propertie或者application.yml,可同时存在。

  基础使用

    application.propertie增加配置:local.ip=192.168.1.1

    application.yml增加配置【使用缩进】:

jdbc:
  name: lhx

  默认位置:classpath、classpath:/config、file:/、file:config下

  注意:application.properties==application-default.properties

1.1、读取方式

方式一、Environment方式读取

context.getEnvironment().getProperty("local.ip","默认值")

@SpringBootApplication
public class App {
    @Bean
    public Runnable createRunnable() {
        return () -> {
            System.out.println("spring boot is running");
        };
    }

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
        context.getBean(Runnable.class).run();
        System.out.println(context.getEnvironment().getProperty("local.ip"));        
        context.close();
    }
}
View Code

其实相当于自定义注入Environment ,然后使用env.getProperty("local.ip")即可

@Component
public class UserConfig {

    @Autowired
    private Environment env;

    public void show() {
        System.out.println("local.ip=" + env.getProperty("local.ip"));
    }
}
View Code

另一种设置默认值方式

HashMap<String, Object> defaultProperties = new HashMap<>();
        defaultProperties.put("server.host", "127.0.0.1");
        application.setDefaultProperties(defaultProperties);

方式二、使用@Value注解

@Value("${local.port}")
    private String localPort;

默认必须有配置项,如果没有配置项可以增加默认值

@Value("${tomcat.port:9090}")
    private String tomcatPort2;

这种的:@Value("tomcat.port") 也可以使用。具体没查

方式三、使用@ConfigurationProperties(prefix="ds")

在application配置文件中增加ds.url=jdbc:mysql://spring

增加读取类

@Component
@ConfigurationProperties(prefix="ds")
public class DataSourceProperties {
    private String url;
    public void show() {
        System.out.println("url"+url);
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    
}
View Code

其他处使用即可。

注意:@ConfigurationProperties(prefix="ds")也支持指定具体路径文件配置@ConfigurationProperties(prefix="ds",localtions="classpath:/ds.properties")

注入数组、集合,在配置文件中增加

ds.host[0]=192.168.1.1
ds.host[1]=192.168.1.2
ds.host[2]=192.168.1.3

代码中

private List<String> hosts = new ArrayList<>();

即可,注意增加getter,setter,

注:支持配置引用配置

name=springboot
aap.name=this is ${name}

1.2、指定具体名称配置

如不使用application.properties,改为app.proerties.

方式一、启动参数中修改:

--spring.config.name=app

或者 有路径的 --spring.config.location=classpath:cong/app.propertis

或者 多个用逗号隔开

或者 file目录    --spring.config.location=classpath:cong/app.propertis,file:E:/app.properties

方式二、文件注解@PropertySource

增加jdbc.properties配置文件

增加Config配置类

@Configuration
@PropertySource("classpath:jdbc.properties")
public class FileConfig {

}

然后使用即可 PropertySource 可以列多个

或者多个可以使用 @PropertySources({@PropertySource("classpath:jdbc.properties")})

@PropertySource: 用于引入外部属性配置,和Environment 配合一起使用。其中ignoreResourceNotFound 表示没有找到文件是否会报错,默认为false,就是会报错,一般开发情况应该使用默认值,设置为true相当于生吞异常,增加排查问题的复杂性.

引入PropertySource,注入Environment,然后就能用environment 获取配置文件中的value值。

二、EnvironmentPostProcessor配置文件扩展

View Code

需要注册到META-INF/spring.factories文件

1.增加此文件,并增加内容

org.springframework.boot.env.EnvironmentPostProcessor=com.lhx.spring.springboot_config.MyEnvironmentPostProcessor

2.增加实现类文件MyEnvironmentPostProcessor

View Code

三、Profiles

增加两个配置文件

方式一、程序读取

在application-dev.properties中添加

jdbc.url=jdbc:mysql://127.0.0.1/spring_dev

在application-test.properties中添加

jdbc.url=jdbc:mysql://127.0.0.1/spring_test

程序使用

SpringApplication app = new SpringApplication(App3.class);
        app.setAdditionalProfiles("test");//test 读取application-test.properties
        ConfigurableApplicationContext context = app.run(args);
        context.getBean(Runnable.class).run();
        System.out.println(context.getEnvironment().getProperty("jdbc.url")); context.close();

注:可在setAdditionalProfiles配置多个,会被覆盖

方式二、参数配置

启动参数增加,多个使用逗号分割,配置多个 多个同时生效

--spring.profiles.active=test

使用

执行java -jar xxx.jar,可以观察到服务端口被设置为8001,也就是默认的开发环境(dev)

执行java -jar xxx.jar --spring.profiles.active=test,可以观察到服务端口被设置为8002,也就是测试环境的配置(test)

执行java -jar xxx.jar --spring.profiles.active=prod,可以观察到服务端口被设置为8003,也就是生产环境的配置(prod)

总结多环境的配置思路: 

  application.properties中配置通用内容,并设置spring.profiles.active=dev,以开发环境为默认配置 

  application-{profile}.properties中配置各个环境不同的内容 

  通过命令行方式去激活不同环境的配置

方式三、@Profile注解

@SpringBootConfiguration
public class MyConfig {
    @Bean
    public Runnable createRunnable() {
        System.out.println("--------1--------");
        return ()->{}; } @Bean @Profile("dev") public Runnable createRunnable2() { System.out.println("--------2--------"); return ()->{}; } @Bean @Profile("test") public Runnable createRunnable3() { System.out.println("--------3--------"); return ()->{}; } }

启动对应环境时候生效

 

 

@ManagedBean注释不起作用,但@Named起作用

@ManagedBean注释不起作用,但@Named起作用

我遇到了麻烦。具有@Named作品的类:

@Named
@SessionScoped
public class UserBean {

@Autowired
UserBo userBo;

public void setUserBo(UserBo userBo) {
    this.userBo = userBo;
}

public String printMsgFromSpring() {
    return userBo.getMessage();
}

}

但这不起作用并产生错误:

javax.servlet.ServletException
javax.faces.webapp.FacesServlet.service(FacesServlet.java:606)根本原因java.lang.NullPointerException
com.mkyong.UserBean.printMsgFromSpring(UserBean.java:24)

@ManagedBean
@SessionScoped
public class UserBean {

@Autowired
UserBo userBo;

public void setUserBo(UserBo userBo) {
  this.userBo = userBo;
}

public String printMsgFromSpring() {
  return userBo.getMessage();
}

}

xhtml页面:

  <?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml"   
  xmlns:h="http://java.sun.com/jsf/html">

<h:body>

    <h1>JSF 2.0 + Spring Example</h1>

    #{userBean.printMsgFromSpring()}


</h:body>

faces-config.xml:

   <?xml version="1.0" encoding="UTF-8"?>
  <faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd"
version="2.1">

<application>
    <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>

    </faces-config>

服务等级:

@Named
public class UserBoImpl implements UserBo{

  public String getMessage() {
        return "JSF 2 + Spring Integration";

  }

}

web.xml:

 <?xml version="1.0" encoding="UTF-8"?>
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
id="WebApp_ID" version="2.5">

    <display-name>JavaServerFaces</display-name>

      <!-- Add Support for Spring -->
   <listener>
      <listener-class>
       org.springframework.web.context.ContextLoaderListener
       </listener-class>
   </listener>
   <listener>
      <listener-class>
       org.springframework.web.context.request.RequestContextListener
       </listener-class>
   </listener>

   <welcome-file-list>
        <welcome-file>default.xhtml</welcome-file>
    </welcome-file-list>

  <servlet>
    <servlet-name>facesServlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
   <servlet-name>facesServlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
   </servlet-mapping>

  </web-app>

applicationContext.xml:

     <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.1.xsd">

   <context:component-scan base-package="com.mkyong" />
     </beans>

Angular environment.ts问题JSON但是environment.prod.ts

Angular environment.ts问题JSON但是environment.prod.ts

在这里您可以看到错误。 现在,在控制台中将其标记,但不在文件中标记。

enter image description here

env.getProperty不起作用Spring PropertyPlaceholderConfigurer

env.getProperty不起作用Spring PropertyPlaceholderConfigurer

我正在使用spring加载属性文件

  <bean id="appProperties">
         <property name="locations" value="classpath:/sample.properties" />
          <property name="ignoreUnresolvablePlaceholders" value="true"/>
    </bean>

当我使用时获得财产价值

@Value("${testkey}") 它的工作正常。

但是当我尝试使用env时

@Resource
 private Environment environment;

environment.getProperty("testkey") // returning null

今天的关于使用纯Java配置的Spring 3.2 @value注释不起作用,但是Environment.getProperty起作用的分享已经结束,谢谢您的关注,如果想了解更多关于005-Spring Boot配置分析-配置文件application、Environment、PropertySource、@Value、EnvironmentPostProcessor、Pr...、@ManagedBean注释不起作用,但@Named起作用、Angular environment.ts问题JSON但是environment.prod.ts、env.getProperty不起作用Spring PropertyPlaceholderConfigurer的相关知识,请在本站进行查询。

本文标签: