自定义SpringbootStarter
Bean的装配方式
1. 单个Bean的装配
(1) @Configuration
+ @Bean
注解
package h.learn.config;
import h.learn.service.StudentService;
import h.learn.service.impl.StudentServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author huang
* @since 2023/7/27
*/
@Configuration
public class RegisterWayByAnnoBean {
@Bean
public StudentService studentService() {
return new StudentServiceImpl();
}
}
2. 批量Bean的装配
(1) @Configuratioin
+ @Bean
+ @Bean
+ …
package h.learn.config;
import h.learn.service.StudentService;
import h.learn.service.impl.StudentServiceImpl;
import h.learn.service.impl.StudentServiceImpl2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author huang
* @since 2023/7/27
*/
@Configuration
public class RegisterWayByAnnoBean {
@Bean
public StudentService studentService() {
return new StudentServiceImpl();
}
@Bean
public StudentService studentService2() {
return new StudentServiceImpl2();
}
}
(2) 通过@Configuration
+@ComponentScan('包路径')
扫描包路径下,类上加上了【@Controller+@Service+@Component+@RestController】注解的类。
①启动类只扫描配置类所在包,和controller所在包
②需要的类上加上service 上述
注解
③创建配置类,@Configuration
+@ComponentScan('需要扫描的包路径')
package h.learn.application;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(value = {
"h.learn.controller","h.learn.config"})
@Slf4j
public class HLearnRegisterWayOfBeanApplication {
public static void main(String[] args) {
SpringApplication.run(HLearnRegisterWayOfBeanApplication.class,args);
log.info("HLearnRegisterWayOfBeanApplication 启动成功");
}