简体   繁体   中英

Springboot How can I inject a non-String value to a property?

I am trying to inject a Path object to a properties. However, it seems like I can only inject a String to a property. So I tried to use the below code to initiate a path properties, but failed. Could anyone suggest me how can to do it?

@Service
public class FilesStorageServiceImpl implements FilesStorageService {

  @Value("${upload.path}")
  private String rootPath;

  private Path root = Path.get(this.rootPath)

  public void doSomething() {
    Files.copy(....)
  }
}

When I debug it, it shows me that root is null. Seems that root path is not initiated.

It depends on how and when the initialization of service variables happens. Easy fix, injection via the setter:

@Service
public class FilesStorageServiceImpl implements FilesStorageService {

  private String rootPath;

  private Path root;

  @Value("${upload.path}")
  public setRootPath(String rootPath) {
    this.rootPath = rootPath;
    root = Path.get(this.rootPath)
  }

  public void doSomething() {
    Files.copy(....)
  }
}

Using setter for value injection, you can have better control over the initialization of root variable.

Injecting the whole object? Probably not the thing you want, since it's not worth the effort to figure out how you're going to serialize, deserialize, and then, inject that object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM