【Spring框架】@Resource注入以及与@Autowired的区别
目录
- 使用@Resource设置name的方式来重命名注入的对象
- 区别
使用@Resource设置name的方式来重命名注入的对象
package com;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;import javax.annotation.Resource;@Controller
public class UserController {@Resourceprivate User user1;public void sayHi(){System.out.println("User"+user1);}
}
区别
1.出身不同: @Resource 来着与 JDK (Java 亲儿子) ,@Autowired 是 Spring 框架提供的。
2.用法不同: @Autowired 支持属性注入、构造方法注入和 Setter 注入,而 @Resource 不支持构造方法注入。
3.支持的参数不同: @Resource 支持更多的参数设置,比如 name、type 设置;@Autowired 只支持required 参数设置。