Spring @Autowired 注解

Spring @Autowired 注解对在哪里和如何完成自动连接提供了更多的细微的控制。

@Autowired 是通过 byType 来自动装配;

  • @Autowired 可注解在成员变量上

    @RestController
    public class HelloController {
      @Autowired
    	private User mUser;
    }
    
  • @Autowired 可注解在方法上

    @RestController
    public class HelloController {
    	private User mUser;
    	@Autowired
    	public void setUser(User user)
    	{
    		this.mUser = user;
    	}
    }
    
  • @Autowired 可注解在构造函数上

    @RestController
    public class HelloController {
    	private User mUser;
    	@Autowired
    	public HelloController(User user)
    	{
    		this.mUser = user;
    	}
    }