@Import

SpringBoot默认会扫描启动类当前的包以及子包,那对于没有在这些包下的类,该怎么注册到IOC容器中呢?

可以使用@Import注解来注册。

@Import具体用法如下:

项目结构如下:

TestController类中需要用到Test1Service, 而启动类未com.gm.test1包中的Application,Test1Service位于com.gm.test2.service包中,如果直接在Test1Service上加@Service注解,SpringBoot根本不会扫描到。

1 创建com.gm.test1.configure包,在该包中创建TestServiceConfig类,该类的内容如下:

package com.gm.test1.configure;

import com.gm.test2.service.Test1Service;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import(Test1Service.class)
public class TestServiceConfig {
}

PS:之所以加上@Configuration注解,是为了让SpringBoot能够扫描到,扫描到之后,SpringBoot会为@Import中的类创建实例,并注册到IOC容器中

2 在TestConroller可以直接通过@Autowire注解来注入Test1Service实例,代码如下:

package com.gm.test1.controller;

import com.gm.test2.service.ITestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestController {
    private static final Logger logger = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private ITestService testService;

    @GetMapping("/test")
    public String test() {
        logger.info("<test> start");

        testService.say("Jim", "Hello");

        return "OK";
    }
}

3 ITestService内容如下:

package com.gm.test2.service;

public interface ITestService {
    void say(String name, String info);
}

4 Test1Service内容如下:

package com.gm.test2.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Test1Service implements ITestService {
    private static final Logger logger = LoggerFactory.getLogger(Test1Service.class);

    @Override
    public void say(String name, String info) {
        logger.info("<say> " + name + " say: " + info);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值