springMVC and Springboot project @value comment is null solution

SpringMVC recent projects and projects encountered getting springboot case configuration items in the configuration file is empty by @value, the following is my solution:

springMVC Project Solution:

service-context configuration files to add the following:

<context:component-scan base-package="com.test">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

All the above classes configured to scan items package name

Because after my service layer and common modules need to get the value of configuration items in the configuration file, but add the above configuration, the service layer I can only get to by @value values ​​of configuration items, common module still can not get to the configuration items value

springboot Project Solution:

We need to add notes in class @Component

E.g:

@Component
public class TestUtil {

  public static boolean enable;

  @Value("${enable}")
  public void setEnable(boolean enable) {
    TestUtil.enable = enable;
  }

 

}

Precautions:

1. @ value acquisition value is null, probably due to the use of static, final modification of variable names:

@Value("${enable}")

public static boolean enable; // Get the value is null

2. A modified static variables need to get to @value variable values, we need to add @PostConstruct

E.g:

@Component
public class TestUtil {

  public static String url;

  @Value("${url}")
  public void setEnable(String url) {
    TestUtil.url = url;
  }

  private static String uri;
  @PostConstruct
  public void init() {
    uri = "http://" + uri;
  }

}

The receiving variable int, long type requires the following values ​​received

@Value("#{${bandwidth}}")
 public Long bandwidth;

Guess you like

Origin www.cnblogs.com/Bud-blog/p/12167926.html