首页IT科技spring bean配置文件详解(spring boot 配置Bean)

spring bean配置文件详解(spring boot 配置Bean)

时间2025-09-08 22:48:30分类IT科技浏览6127
导读:package com.example.demo.config; import com.example.demo.entiy.User;...

package com.example.demo.config; import com.example.demo.entiy.User; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /* Configuration注解修饰类,作用如下 1.被修饰的类注入ioc容器                。 2.被spring boot识别为配置类                       。可以继承WebMvcConfigurer修改spring boot配置 */ @Configuration(proxyBeanMethods = true) // proxyBeanMethods 属性默认为true // 为true则开启代理                ,将代理对象存储进ioc容器        。其内部被@Bean注解修饰的方法既是共有方法                       ,被提取被代理            。 public class BeanConfig { @Bean // 被@Bean修饰的方法        ,返回值存入ioc容器            ,名称为方法名                       ,类型是方法类型 // @Bean("user01") 通过传入参数修改名称 public User user() { return new User("张三",18); } }

测试

package com.example.demo; import com.example.demo.entiy.User; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class Demo9Application { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(Demo9Application.class, args); // 通过上下文对象获取Bean User user01 = context.getBean("user", User.class); User user02 = context.getBean("user", User.class); System.out.println(user01); System.out.println(user02); System.out.println(user01 == user01); } }

结果

User{name=张三, age=18} User{name=张三, age=18} true

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
井陉新闻网(井陉贴吧2020年)