Since the title says @autowired is not recommended, there must be a good alternative, which is @resource. So what’s @resource? Let’s compare @Resource and @Autowired.

The difference between a

The @autowired annotation comes with Spring

@resource is provided by J2EE and supported by Spring

The difference between the two

@AutoWired defaults to assembly by type

@Resource is assembled by name by default

Let’s look at the source code for @resource.

@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})


public @interface Resource {

String name(a) default ""; Class<? > type()default Object.class;

Resource.AuthenticationType authenticationType(a) default Resource.AuthenticationType.CONTAINER;

boolean shareable(a) default true;

String description(a) default "";

String mappedName(a) default "";

String lookup(a) default "";

public static enum AuthenticationType {



private AuthenticationType(a) {}}}Copy the code

You can see from above that @resource has two important properties: name and type.

It says “assembly by name by default”, but it can be handled by type.

Spring resolves the name attribute of the @Resource annotation to the name of the bean, and the Type attribute to the type of the bean. So if you use the name attribute, you use the auto-injection policy of byName, and if you use the type attribute, you use the auto-injection policy of byType. If neither the name nor the type attribute is specified, the byName auto-injection policy is used through the reflection mechanism.

@Resource (@resource) @resource (@resource)

  • If both name and type are specified, a unique matching bean is found from the Spring context for assembly, and an exception is thrown if not found

  • If name is specified, the Spring context looks for a bean whose name (ID) matches and assembs it. If not, an exception is thrown

  • 3 If type is specified, a unique bean with a matching type is found from the Spring context for assembly. If no or more beans are found, an exception is thrown

  • 4 If neither name nor type is specified, the byName mode is used for the assembly. If there is no match, the match is rolled back to a primitive type, and if there is a match, auto-assembly is performed.

@ the Resource is roughly finished, feels the @autowired and @ Resource about the same, only one is to eradicate types, one is according to the name of the injection, it is recommended to use @ the Resource?

Well, @Resource comes with Java! And there will be no yellow hint line in idea. If @autowired is used, the idea will prompt “field injection is not recommended”. This is a benefit for people who like to be clean. Why don’t you use it?

A cat programmer, like please pay attention to the public number “programmer Xiao Zhu”