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

 

 

 

@Autowired 注解是Spring框架提供的一种依赖注入方式,用于自动装配指定类型的bean对象到对应的变量或构造函数中。这样可以方便地管理和使用各种工具类。 在给工具类注入的过程中,可以使用@Autowired 注解来标注变量或构造函数。例如,中的代码是将Star类型的bean对象注入到TestUtil类中的star变量中。通过这种方式,我们可以在TestUtil类中直接使用star对象的方法。 此外,中的代码演示了如何在构造函数上使用@Autowired 注解来实现对工具类注入。通过在构造函数中添加@Autowired注解,Spring框架会自动将符合条件的bean对象注入到构造函数中的参数中。 在使用@Autowired 注入工具类时,还需要在Spring的配置文件中进行相关配置。一般需要使用<context:component-scan>标签来指定扫描的包路径,确保Spring能够自动扫描到工具类并进行注入。例如,中的代码展示了如何在配置文件中配置扫描ts.util包。 总之,通过使用@Autowired注解,我们可以方便地将工具类注入到需要使用的地方,实现依赖的自动装配。这样可以提高代码的可维护性和灵活性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [工具类使用@Autowired注入](https://blog.csdn.net/qq_41482600/article/details/111606637)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值