@Autowired annotaded method vs @PostConstruct annotaded method

119 views Asked by At

What is the difference between using @Autowired or @PostConstruct on a method since they offer the same result (according to what I have understood from different sources)

UPDATE: Here is an example of my class in which I get the same result if I use @Autowired or @PostCosntruct to annotate the method configClient()

@Service
public class AwsSTSService {

  @Autowired
  private AwsConfiguration awsConfiguration;


  public CustomCredentials getCredentials()  {
        ......
    return customCredentials;

  }


  @Autowired // or @PostConstruct
  private void configClient()  {

    CustomCredentials customCredentials = getCredentials();
    awsConfiguration.setAwsAccessKey(customCredentials.getAccessKeyId());
    awsConfiguration.setAwsSecretKey(customCredentials.getSecretAccessKey());
    awsConfiguration.setExpiration(customCredentials.getExpiration());
    awsConfiguration.setSessionToken(customCredentials.getSessionToken());
  }
}
1

There are 1 answers

0
Iman Ahrari On

Actually, they don't have anything in common. @Autowired could be used to inject any dependency in your beans (components), on the other hand, @PostConstruct can be used on methods of your beans, and spring boot will call that method after that bean was created (for purposes like populating a database or calculating some initial data).

You can see how this article used these two annotations in its example codes https://www.baeldung.com/spring-postconstruct-predestroy#postConstruct