8 formas de definir beans en SpringBoot
1. @frijol
@Bean
publicZlmService zlmService(){
return new ZlmService();
}
2. @Componente
@Component
public class ZlmService{
}
3. @Controlador @RestController @Servicio @Repositorio
@Controller
public class ZlmController{
}
4. @ControllerAdvice @RestControllerAdvice
@ControllerAdvice
public class ZlmControllerAdvice implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
System.out.println("body write");
return body;
}
}
Los resultados devueltos se pueden procesar
5. @Configuración
bean de clase de configuración
@Configuration
public class AppConfig{
}
6. @Importar
public class ZlmService {
public String info(String info){
System.out.println("service中info () execute");
return info;
}
}
@Import(ZlmService.class)
@SpringBootApplication
public class Application {
}
7. Definición de frijol
public class ZlmImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
/**
* 注册bean到spring容器中
* @param importingClassMetadata
* @param registry
* @param importBeanNameGenerator
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
beanDefinition.setBeanClass(ZlmService.class);
registry.registerBeanDefinition("zlmService",beanDefinition);
}
}
@Import(ZlmImportBeanDefinitionRegistrar.class)
@SpringBootApplication
public class Application {
}
8.xml
@ImportResource("classpath:spring.xml")
@SpringBootApplication
public class Application {
}
<bean id="zlmService" class="com.zlm.ZlmService"/>