java SpringBoot 自己写的类 调用 service 层的方法

本文通过示例代码展示了如何使用Spring框架的@Component注解来注册自定义类,并通过@PostConstruct注解实现组件的初始化逻辑。同时介绍了@Autowired依赖注入及静态方法调用。

直接上代码


// 加 @Component 注解 先把自己创建的类 MyClass 在Spring 中 注册成 组件
@Component
public class MyClass {

    // 注入 需要 调用的 service 类
    @Autowired
    protected MyService myService;

    // 创建 自己类 的 私有 属性
    private static MyClass myClass ;
    
    //  新增init 方法  @PostConstruct 注解 作用 在启动项目时 执行该方法
    @PostConstruct
    public void init() {
        // 把 类本身 赋予变量  myClass
        myClass = this;
        // 把 初始化加载的 nettyMeterDataService 属性 赋值给本类
        myClass.MyService = this.MyService;

    }

    // 测试方法
    public static void main(String[] args) {
        // 调用方式  本类名.service类.service类中具体方法
        myClass.MyService.insertData(null);
    }


}
Spring Boot 的 `main` 方法中利用反射调用 `service` 方法,可按如下步骤进行: 1. 获取 Spring 应用上下文; 2. 从应用上下文中获取 `service` Bean; 3. 使用反射调用 `service` 中的方法。 以下是示例代码: ```java import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import java.lang.reflect.Method; @SpringBootApplication public class MainApplication { public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); } @Bean public CommandLineRunner commandLineRunner(ApplicationContext context) { return args -> { // 从应用上下文中获取 service Bean Object serviceBean = context.getBean(YourService.class); try { // 获取要调用方法 Method method = YourService.class.getMethod("yourMethodName", String.class); // 准备方法参数 String param = "exampleParam"; // 使用反射调用方法 Object result = method.invoke(serviceBean, param); // 处理方法返回结果 System.out.println("Method result: " + result); } catch (Exception e) { e.printStackTrace(); } }; } } class YourService { public String yourMethodName(String param) { return "Result for " + param; } } ``` 在上述代码中,`MainApplication` 是 Spring Boot 应用的主。在 `commandLineRunner` 方法里,借助 `ApplicationContext` 获取 `YourService` 的 Bean 实例。之后,使用反射获取 `yourMethodName` 方法,准备参数并调用方法,最后处理方法的返回结果。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

OOObject

你的鼓励是我创作的最大源泉

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值