当前位置: 首页> 娱乐> 影视 > 初学Spring之 JavaConfig 实现配置

初学Spring之 JavaConfig 实现配置

时间:2025/7/11 23:57:23来源:https://blog.csdn.net/m0_58838332/article/details/140211992 浏览次数:0次

使用 Java 方式配置 Spring

写个实体类:

@Component 表示这个类被 Spring 接管了,注册到了容器中

package com.demo.pojo;import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;@Component //这个类被Spring接管了,注册到了容器中
public class User {private String name;public String getName() {return name;}@Value("张三") //属性值注入public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "User{" +"name='" + name + '\'' +'}';}
}

写个配置类:

@Configuration 会被 Spring 容器托管,注册到容器中,因为他本来就是一个 @Component

@Configuration 代表这是一个配置类,和 beans.xml 一样

再写个方法:

@Bean:

注册一个 bean,相当于 bean 标签

这个方法的名字,相当于 bean 标签中的 id 属性

这个方法的返回值,相当于 bean 标签中的 class 属性

package com.demo.config;import com.demo.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;//@Configuration会被Spring容器托管,注册到容器中,因为他本来就是一个@Component
//@Configuration代表这是一个配置类,和beans.xml一样
@Configuration
public class Config {/*注册一个bean,相当于bean标签这个方法的名字,相当于bean标签中的id属性这个方法的返回值,相当于bean标签中的class属性*/@Beanpublic User getUser(){return new User(); //return返回要注入到bean的对象}
}

扫描:@ComponentScans("xx")

导入其他类:@Import(xx.class)

写个测试类:

如果完全使用了配置类方式去做,

只能通过 AnnotationConfig 上下文来获取容器,

通过配置类的 class 对象加载

import com.demo.config.Config;
import com.demo.pojo.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(Config.class);User getUser = (User) context.getBean("getUser");System.out.println(getUser.getName());}
}
关键字:初学Spring之 JavaConfig 实现配置

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: