SpringBoot java配置类@Configuration 的两种写法


首先在Springboot项目中,件一个java类,使用注解@Configuration  ,则这个类是SpringBoot bean的创建的配置文件类,,这种配置文件类有两种写法 1.使用包扫描 ,创建bean2. 使用函数创建bean

1.通过包扫描,将包下所有注解类,注入到spring容器中 

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration //1使用配置注解 ,表示这个类是配置文件
@ComponentScan("com.wisely.highlight_spring4.ch1.di") //2使用扫描注解
public class DiConfig {
}

2.不使用扫描 ,注解。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration //1表示配置文件 
public class JavaConfig {
  @Bean //2spring调用这个方法直接把FunctionService这个类实例加入到spring容器中
  public FunctionService functionService(){
    return new FunctionService();
  }
}
FunctionService也是没有使用注解
//1没有加Service注解
public class FunctionService {
  public String sayHello(String word){
  return "Hello " + word +" !";
  }
}

以上两种方法是在开发中常用的应该是第一种 ,使用注解可以大量减少代码量。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM