Search code examples
springspring-ioc

What is the different between Aware interface and @Autowired


In Spring, I can get Spring's objects using Aware interfaces:

@Component
class TestAware : ApplicationContextAware, EnvironmentAware {
    override fun setEnvironment(environment: Environment) {
        println("Server port" + environment.getProperty("server.port"))
    }

    override fun setApplicationContext(applicationContext: ApplicationContext) {
        println("ApplicationContext" + applicationContext.displayName)
    }
}

But then I can do the same thing using @Autowired:

@Component
class AutowiredTest {
    @Autowired
    fun constructor(env: Environment, appCtx: ApplicationContext) {
        println("ApplicationContext From Autowired" + appCtx.displayName)
        println(env.getProperty("server.port"))
    }

}

So what is the difference between them, and in which cases I must use Aware but not @Autowired?


Solution

  • Traditionally @Autowired is the core dependency injection method, preferred in the constructor to inject necessary beans that will be utilized by said object.

    Aware, more specifically I think you mean ApplicationContextAware yes? This is meant as more of a higher view so the implementing class can alter the context it has been created in. The entire meaning and approach is different. If you need the functionality of another bean, @Autowire it (inject it) into the using class. If you need to manipulate your context, such as bootstrapping other beans, making decisions based on what has been injected as a whole, then this would be the approach used for Aware.

    Did I miss the mark?