spring之普通工具类使用@Autowired依赖注入

使用到的注解@Component、@Autowried、@PostConstruct

一、类头部需要添加@Component ,把当前类注册成一个bean

二、在需要注入的类引入Autowired

三、使用@PostConstruct注解执行类所需的初始化操作

四、在别的类使用这个类的时候不能用new,只能用注入的方式

如下实例: 

@Component
public class UtilAutoInTest {
	
	@Autowired
	private HsCollegeServiceI hsCollegeServiceI;
	
	public static UtilAutoInTest autoInTest;
	
	@PostConstruct
	public void init(){
		autoInTest = this;
	}
	
	public static void test(){
		List<InfoCollege> colleges = autoInTest.hsCollegeServiceI.combobox();
	}
	
	public void test2(){
		List<InfoCollege> colleges = hsCollegeServiceI.combobox();
	}
	
}

执行顺序:先执行构造方法,再注入依赖,最后执行初始化操作
即Constructor > @Autowired > @PostConstruct

其他类调用该类的方法 :

@Controller
public class UserConstroller{
    @Autowired
	private UtilAutoInTest autoInTest;
    
    @GetMapping("/user")
    public void test(){
        autoInTest.test();
		autoInTest.test2();
    }
}

 

@PostConstruct 修饰一个非静态的void()方法

@PostConstruct

public void someMethod(){}

或者

public @PostConstruct void someMethod(){}

要将对象p注入到对象a,那么首先就必须得生成对象a和对象p,才能执行注入。所以,如果一个类A中有个成员变量p被@Autowried注解,那么@Autowired注入是发生在A的构造方法执行完之后的。

如果想在生成对象时完成某些初始化操作,而偏偏这些初始化操作又依赖于依赖注入,那么久无法在构造函数中实现。为此,可以使用@PostConstruct注解一个方法来完成初始化,@PostConstruct注解的方法将会在依赖注入完成后被自动调用。

Constructor >> @Autowired >> @PostConstruct

 

 

 

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值