Skip to content

Autowired

Wuyi Chen edited this page Jun 18, 2019 · 4 revisions

Autowired a Field

Field is a concrete class

If the type of the field is a concrete class, @Autowired annotation will automatically inject the object of that class into that field directly, you don't have to implement the getters and the setters. For example:

Concrete Class

@Component
public class ServiceConfig{
    /* omit the implementation */
}

Class uses @Autowired

@Service
public class LicenseService {
    @Autowired
    ServiceConfig config;
	   
    /* omit other functions */
}   

After using @Autowired, you can use the config field directly in the functions of the LicenseService class.

Field is an interface

If the type of the field is an interface, it will automatically inject the object of the concrete class which implements that interface. For example:

Interface

public interface OrganizationRedisRepository {
    /* define methods */
}

Concrete Class

@Repository
public class OrganizationRedisRepositoryImpl implements OrganizationRedisRepository {
    /* implements methods */
}

Class uses @Autowired

@Component
public class OrganizationRestTemplateClient {
    @Autowired
    OrganizationRedisRepository orgRedisRepo;

    /* omit other functions */
}

After using @Autowired, the dependency injection of orgRedisRepo field will be finished automatically and it will map to the OrganizationRedisRepositoryImpl class.

References

Clone this wiki locally