SpringBoot中定义Bean的8种方式

SpringBoot中定义Bean的8种方式

    • 1. @Bean
    • 2. @Component
    • 3. @Controller @RestController @Service @Repository
    • 4. @ControllerAdvice @RestControllerAdvice
    • 5. @Configuration
    • 6. @Import
    • 7. BeanDefinition
    • 8.

1. @Bean

@Bean
publicZlmService zlmService(){
	return new ZlmService();
}

2. @Component

@Component
public class ZlmService{

}

3. @Controller @RestController @Service @Repository

@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;
    }
}

可以对返回结果进行处理

5. @Configuration

配置类Bean

@Configuration
public class AppConfig{

}

6. @Import

public class ZlmService {

    public String info(String info){
        System.out.println("service中info () execute");
        return info;
    }
}
@Import(ZlmService.class)
@SpringBootApplication
public class Application {
}

7. BeanDefinition

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.

@ImportResource("classpath:spring.xml")
@SpringBootApplication
public class Application {
}
<bean id="zlmService" class="com.zlm.ZlmService"/>

你可能感兴趣的:(spring,boot,后端,java)