This is fairly straight forward, but I can't figure out what the problem is. I am trying to access environment variables from application.properties
but when I do so like this:
import org.springframework.core.env.Environment;
public class MailService {
@Autowired
private static Environment env;
...
...
...
public static void send(){
System.out.println("env {}" env.getProperty("AWS_ACCESS_KEY_ID"));
}
Then I get a NullPointerException.
So what is going on? Why am I getting an error. Here is my application.properties
file with fake values:
AWS_ACCESS_KEY_ID="Asdsds"
AWS_SECRET_KEY="sdsdsdsdsdsd"
CodePudding user response:
Autowired works only on class instances managed by Spring. The value is injected after the constructor. Your class isn't managed by Spring and your environment property is static.
Something like this will work:
@Service // Will be instantiated by spring
public class MailService {
private static Environment env;
@Autowired // This will be called after instantiation
public void initEnvironment(Environment env){
MailService.env = env;
}
public static void send(){
// NullPointerException will be thrown if this method is called
// before Spring created the MailService instance
System.out.println("env {}" env.getProperty("AWS_ACCESS_KEY_ID"));
}
}
You should avoid using static method if you want access to object managed by Spring.
Instead let Spring manage all your class instances and inject your service when you need it.
@Service
class AnotherService {
@Autowired
private MailService mailSvc;
...
CodePudding user response:
Your class should have the @Service
annotation or Configuration
:
@Service
public class MailService {
@Autowired
private Environment env;
...
}
Read this for more details on why you should avoid static
.