当前位置: 首页 > 新闻动态 > 软件编程

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

作者:用户投稿 浏览: 发布日期:2026-01-11
[导读]:这篇文章主要介绍了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中随处可见!

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

免责声明:转载请注明出处:http://sczxchw.cn/news/499709.html

扫一扫高效沟通

多一份参考总有益处

免费领取网站策划SEO优化策划方案

请填写下方表单,我们会尽快与您联系
感谢您的咨询,我们会尽快给您回复!