maven打包项目,然后给其他项目引用

文章讲述了如何在SpringBoot项目中,将A项目打包为jar并引入B项目,同时利用ComponentScan注解实现对A项目REST控制器的访问。还展示了如何通过@Autowired注入依赖并操作TeachingService类的方法。
摘要由CSDN通过智能技术生成

A项目(这个项目需要被打包,作为被引入的项目),不需要启动类,因为作为公共模块被B项目引入:

package com.yunya.mvndependontest.rest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/teacher")
public class TeacherRest {

    @RequestMapping("/say")
    public String say() {
        String word = "好好学习,天天向上!";
        System.out.println(word);
        return word;
    }

}
Teaching Service类,包含math 和 chinese方法:

package com.yunya.mvndependontest.service;

import org.springframework.stereotype.Service;

@Service
public class Teaching {

    public String math() {
        return "教数学啦";
    }

    public String chinese() {
        return "教中文啦";
    }

}

B项目:引入打包后的A项目(gav格式引入),启动端口是:8082

MvnDependOnParentTestApplication 启动类文件:
注意务必要使用@ComponentScan注解将A项目的restcontroller路径也引入,否则访问A项目restful接口路径(/teacher/say)会提示找不到地址。
package com.yunya.mvndependonparenttest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan("com.yunya")
public class MvnDependOnParentTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(MvnDependOnParentTestApplication.class, args);
    }

}
Student RestController类,该类中调用A项目的Teaching Service类的方法math:

package com.yunya.mvndependonparenttest.rest;

import com.yunya.mvndependontest.service.Teaching;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/student")
public class Student {

    @Autowired
    Teaching teaching;

    @RequestMapping("/study")
    public String study() {
        String studyContent = "学生学到了一首诗:床前明月光,疑是地上霜。";
        System.out.println(studyContent);

        // 调用引入的A项目的teaching service类中的math方法
        String mathContent = teaching.math();
        System.out.println(mathContent);

        return studyContent;
    }
}

访问效果:
访问B项目地址:localhost:8082/teacher/say,如下效果:
在这里插入图片描述
访问B项目地址:localhost:8082/student/study,如下效果:
在这里插入图片描述

引用:
把一个项目打成jar包并引入其他项目中

springboot引入其他项目jar包并实现对数据库的操作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值