1
votes

I have a class like this -

@Service
public class SomeClass {

@Autowired
Environment env;

private String property;

@Value("${pty}")
public void setPty(String pty) {
    pty = environment.getProperty("pty");
   } 
}

I'm trying to inject the 'pty' variable from another class 'Environment' which is autowired and I get this exception when my server startups

Error creating bean with name 'someClass': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void service.facade.ActionFacade.setPty(java.lang.String); nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'pty' in string value "${pty}"

3
Post your spring config.Maroun

3 Answers

1
votes

The exception is because there is no property pty in your Spring context. @Value lookup the placeholder 'pty' in the resource files loaded.

In your case it is not required as you need to get it from Environment class which you have Autowired already, below code will give you the idea.

@Service
public class SomeClass {

 @Autowired
 Environment env;
 private String property;

 @PostConstruct
 public void init(){
    property=env.getProperty("pty");
 }
}
0
votes

Try @PostConstruct

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization.

@PostConstruct
public void init() {
    property = env.getProperty("pty");
}
0
votes

You can do this with the help of Spring bean life cycles: 1. InitializingBean -> afterPropertiesSet 2. @PostConstruct

public class EmployeeService implements InitializingBean{

    private Employee employee;

    public Employee getEmployee() {
        return employee;
    }

    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

@PostConstruct
public void init() {
   property = env.getProperty("pty");
}

    @Override
    public void afterPropertiesSet() throws Exception {

    }
}

enter image description here