Spring 使用JavaConfig实现配置的方法步骤

前端之家收集整理的这篇文章主要介绍了Spring 使用JavaConfig实现配置的方法步骤前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

不使用Spring的XML配置,全权交给java来做!

JavaConfig是Spring的一个子项目,在Spring4之后,它称为了Spring的核心功能

实体类:

package com.lrx.poji;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//说明这个类被Spring注册到了容器中
@Component
public class User {
 @Value("lixin")
 private String name;

 public String getName() {
   return name;
 }

 public void setName(String name) {
   this.name = name;
 }

 @Override
 public String toString() {
   return "User{" +
       "name='" + name + '\'' +
       '}';
 }
}

配置文件

package com.lrx.config;

import com.lrx.poji.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

//这个也会被Spring容器托管,因为它本来就是一个@Component
// @Configuration代表一个类,就和我们之前的ApplicationContext.xml是一样的
@Configuration
@ComponentScan("com.lrx.poji")
public class LiConfig {
  //注册一个bean,就相当于xml写的一个bean标签
  //这个方法的名字就相当于bean标签中的ID属性
  //方法的返回值相当于bean标签中的class属性
  @Bean
  public User getUser(){
    return new User();  //就是要注入到bean的对象
  }
}

测试类:

import com.lrx.config.LiConfig;
import com.lrx.poji.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
  public static void main(String[] args) {
    //如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig上下文来获取容器
    // 然后通过配置类的class对象来加载!
    ApplicationContext context=new AnnotationConfigApplicationContext(LiConfig.class);
    User getUser= (User) context.getBean("user");
    System.out.println(getUser.getName());
  }
}

这种纯Java的配置方式在Spring Boot中随处可见!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

原文链接:https://www.f2er.com/java/534982.html

猜你在找的Java相关文章