0

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());
  }
}
Midovsky
  • 11
  • 2
  • 1
    Does this answer your question? [How Spring Boot Autowired and Post Construct work?](https://stackoverflow.com/questions/60225433/how-spring-boot-autowired-and-post-construct-work) – Sangam Belose Sep 01 '22 at 13:56

1 Answers1

2

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