Skip to content

Doc: Different behavior for @Named and @Component [SPR-14087] #18659

Closed
@spring-projects-issues

Description

@spring-projects-issues

MD Sayem Ahmed opened SPR-14087 and commented

I am trying to understand the differences between these two annotations and how they affect injection in Spring. Consider the following piece of code -

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ExternalPropertiesHolder {}

When I mark a class with this annotation -

@ExternalPropertiesHolder
public class SomeProperties {}

and then this dependency is injected using @Inject, it works perfectly -

@Service
public class SomeService {
    private SomeProperties someProperties;

    @Inject
    public SomeService(SomeProperties someProperties) {
        this.someProperties = someProperties;
    }
}

However, when I replace @Component with @Named -

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Named           // --> Here!
public @interface ExternalPropertiesHolder {}

Then the injection fails with the usual bean not found exception -

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.hogehoge.SomeProperties] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}

Shouldn't they behave the same way?

I am using Spring Boot 1.3.3.RELEASE version, and using JDK 8 to compile my application.


Reference URL: http://stackoverflow.com/questions/36203489/spring-differences-between-named-and-component

Backported to: 4.2.7

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)status: backportedAn issue that has been backported to maintenance branchestype: taskA general task

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions