SpringBoot第三方jar包Bean注入的方法

方法一:使用@Bean注解(不建议)

首先启动类SpringbootRegisterApplication扫描的是本包以及子包的内容,我们只需在启动类中声明一个方法即可。

@SpringBootApplication
public class SpringbootRegisterApplication {

    public static void main(String[] args) {
        ApplicationContext context=SpringApplication.run(SpringbootRegisterApplication.class, args);
        System.out.println(context.getBean("country"));		//判断是否注入成功
    }
    @Bean										//也可以Bean("name") name为Bean对象名
    public Reolver resolver(){			//默认Bean对象就是方法名
    	return new Resolver();
    }
}

方法二:在配置类中集中注册

在启动类所在包中创建配置类

@Configuration
public class CommonConfig {
    @Bean
    public Country country()
    {
        return new Country();
    }

    @Bean
    public Province province(Country country)
    {
        return new Province();
    }
}

方法三:使用@Import注解

在启动类上导入需要配置的类对象即可,一般为配置类和ImportSelector的接口实现类。

一、导入配置类

@Import({CommonConfig.class})
@SpringBootApplication
public class SpringbootRegisterApplication {
    public static void main(String[] args) {

        ApplicationContext context=SpringApplication.run(SpringbootRegisterApplication.class, args);
        System.out.println(context.getBean("country"));
        System.out.println(context.getBean("province"));

    }
     }

二、导入Selector接口实现类(适用于导入多个类)

public class CommonImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        //
        List<String> imports=new ArrayList<>();
        InputStream is=CommonImportSelector.class.getClassLoader().getResourceAsStream("common.imports");		//从配置文件中获取配置类。
        BufferedReader br=new BufferedReader(new InputStreamReader(is));
        String line=null;
        try {
            while((line=br.readLine())!=null)
            {
                imports.add(line);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        finally {
            if(br!=null)
            {
                try {
                    br.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return imports.toArray(new String[0]);		//可以简洁的导入多个类
    }
}

在启动类上添加@Import(CommonImportSelector.class)即可,

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值