【Spring框架】@Resource注入以及与@Autowired的区别

使用@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 {
    
    
    @Resource
    private 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 参数设置。

猜你喜欢

转载自blog.csdn.net/weixin_61341342/article/details/131964305
今日推荐