springboot安装第三方jar包并把jar包对象注入到ioc容器的流程及源码

基本思路流程:win+r打开运行输入cmd打开命令输入界面,输入安装命令

mvn install:install-file -Dfile=E:\maven-example\common-user.jar -DgroupId=cn.itcast -DartifactId=common-pojo -Dversion=1.0 -Dpackaging=jar

-Dfile=jar包在本地磁盘的路径
-DgroupId=组织名称
-DartifactId=项目名称
-Dversion=版本号
-Dpackaging=打包方式

请把-Dfille=jar包地址更换为自己的jar包地址

注意命令安装jar包必须要maven环境变量要配置好,在apach-maven安装目录conf下settings.xml里的内容是否完整,文件里不能有多余的空格。如果出错命令窗口会提示出错的行数。

依赖包安装完后,新建springboot-register项目,在pom文件里导入安装的jar包依赖

        <!--导入外部依赖-->
        <dependency>
            <groupId>cn.itcast</groupId>
            <artifactId>common-pojo</artifactId>
            <version>1.0</version>
        </dependency>

将jar包里面的类注入到ioc容器有两种方式

1、@Bean加在@Configruation的类下的方法上。必须在启动类同等目录或者子类里,才能被扫描被加载

2、@Import 加在启动类(@SpringBootApplication)的类上,该注释一般用在导入配置类、ImportSelector接口实现类。用在不同于启动类同等目录或者子类里。

首先展示@Bean使用流程:

写一个名为CommonConfig配置类用@Configuration注解,在配置类用名为jar包里面类名的方法,返回一个jar包的实体类。并用@Bean注册到ioc容器里。

具体过程是在启动类同等目录或其子类创建config包,在包内创建配置类CommonConfig并在类中加入代码

@Configuration
public class CmonnonConfig {
    @Bean
    public User user(@Value("${User.id}") int id,@Value("${User.username}") String username,@Value("${User.password}") String password,@Value("${User.email}") String email){
        User user=new User();
        user.setId(id);
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        return user;
    }

    @Bean
    public UserProfile userProfile(){
        UserProfile userProfile=new UserProfile();
        userProfile.setId(01);
        userProfile.setAddress("西部大厦");
        userProfile.setBankcard("62012345623");
        return userProfile;
    }

用户配置属性可有外部输入,在资源文件夹resources下创建application.yml文件,写入如下代码

User:
  id: 1001
  username: "李部长"
  password: "affff123"
  email: "[email protected]"

UserProfile:
  id: 101
  address: "ddddjjjj"
  bankcard: "1233444"

在@Bean方法参数里用@V

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值