• Spring Java配置


    Java配置

    Java配置是Spring 4.x推荐的配置方式,可以完全替代xml配置;
    Java配置也是Sping Boot 推荐的配置方式。
    Java配置是通过@Configuration和@Bean来实现的。
    @Configuration 声明当前类是一个配置类,相当于一个Spring配置的xml文件。
    @Bean 注解在方法上,声明当前方法的返回值为一个Bean。
    使用原则:
    全局配置使用Java配置(如数据库相关配置、MVC相关配置),业务Bean的配置使用注解配置
    (@Service、@Component、@Repository、@Controlle).

    实例

    编写功能类的Bean

    package com.wisely.highlight_spring4.ch1.javaconfig;
    //1
    public class FunctionService {

    public String sayHello(String word){
    return "Hello " + word +" !";
    }
    }

    代码解释
    此处没有使用@Service声明Bean。


    使用功能类的Bean
    package com.wisely.highlight_spring4.ch1.javaconfig;

    import com.wisely.highlight_spring4.ch1.javaconfig.FunctionService;
    //1
    public class UseFunctionService {
    //2
    FunctionService functionService;

    public void setFunctionService(FunctionService functionService) {
    this.functionService = functionService;
    }

    public String SayHello(String word){
    return functionService.sayHello(word);
    }
    }
    代码解释
    此处没有使用@Service声明Bean
    此处没有使用@Autowired注解注入Bean


    配置类
    package com.wisely.highlight_spring4.ch1.javaconfig;

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;

    @Configuration //1
    public class JavaConfig {
    @Bean //2
    public FunctionService functionService(){
    return new FunctionService();
    }

    @Bean
    public UseFunctionService useFunctionService(){
    UseFunctionService useFunctionService = new UseFunctionService();
    useFunctionService.setFunctionService(functionService()); //3
    return useFunctionService;

    }
    }

    代码解释
    使用@Configuration注解表明当前类是一个配置类,这意味着这个类里可能有0个或者多个@Bean注解,此处没有使用包扫描,是因为所以的Bean都在此类中定义了。
    使用@Bean注解声明当前方法FunctionService的返回值是一个Bean,Bean的名称是方法名。
    注入FunctionService的Bean时候直接调用 functionService().
    package com.wisely.highlight_spring4.ch1.javaconfig;

    import org.springframework.context.annotation.AnnotationConfigApplicationContext;

    public class Main {
    public static void main(String[] args) {
    AnnotationConfigApplicationContext context =
    new AnnotationConfigApplicationContext(JavaConfig.class);

    UseFunctionService useFunctionService = context.getBean(UseFunctionService.class);

    FunctionService functionService = context.getBean(FunctionService.class);

    System.out.println(useFunctionService.SayHello("java config"));

    System.out.println(functionService.sayHello("faunjoe"));

    context.close();
    }
    }


    
    


  • 相关阅读:
    jedata日期控件的开始结束日期设置
    springMVC中对HTTP请求form data和request payload两种数据发送块的后台接收方式
    Java Code Examples for org.codehaus.jackson.map.DeserializationConfig 配置
    Struts 2与AJAX(第二部分)
    在Struts 2中实现文件上传
    Strus 2的新表单标志的使用
    在Struts 2中实现CRUD
    Struts 2与AJAX(第三部分)
    Struts 2中的OGNL
    GridView中实现自定义时间货币等字符串格式
  • 原文地址:https://www.cnblogs.com/faunjoe88/p/5675195.html
Copyright © 2020-2023  润新知