
在 spring boot 中,当注入普通类到其他 service 时,可能会遇到错误,因为普通类没有被自动管理。
spring boot 中的组件化注解(如 @component、@service)用于指示 spring 管理类和 bean,并允许它们被注入到其他组件中。在问题中提供的代码中,printinvoiceservice 是一个普通类,没有使用任何组件化注解。
为了解决这个问题,需要将 printinvoiceservice 类标记为一个组件。这可以有两种方法:
1. 使用组件化注解
在类上添加 @component 或 @service 注解,例如:
@service
public class printinvoiceservice {
// ...
} 2. 手动注入(推荐)
如果 printinvoiceservice 类中有依赖关系需要被注入,可以使用 springutils 类来手动获取 spring 容器中的 bean。
// 创建 springutils 类
@component
public class springutils implements applicationcontextaware {
// ...
public static <t> t getbean(string beanname) {
return (t) applicationcontext.getbean(beanname);
}
} 然后在需要注入 printinvoiceservice 的 service 中使用 getbean 方法,例如:
@Service
public class FgStoServiceImpl implements FgStoService {
// ...
private PrintInvoiceService printInvoiceService = SpringUtils.getBean("printInvoiceService");
// ...
} 通过使用组件化注解或手动注入,可以确保 printinvoiceservice 类被 spring 管理,并可以被其他 service 注入。
以上就是Spring Boot中如何正确注入普通类到Service中?的详细内容,更多请关注知识资源分享宝库其它相关文章!







发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。