最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Spring注解@Configuration与@Bean注册组件代码使用解析
时间:2022-06-29 01:44:36 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下Spring注解@Configuration与@Bean注册组件代码使用解析,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
原始Spring开发
Person.java
准备Person.java类:
package com.jektong.spring;
public class Person {
private String name;
private int age;
public Person() {
super();
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
pom.xml
在pom文件导入Spring基本依赖:
4.0.0 com.jektong maven01 0.0.1-SNAPSHOT maven01 maven01 org.springframework spring-context 4.3.12.RELEASE
bean.xml
在没有使用Spring注解开发之前,我们通常会通过一个xml配置文件(bean.xml)去将我们需要使用的对象通过Bean的方式去注入到Spring容器中。
下面就是将Person作为对象注入Spring容器中:
PersonTest.java
使用一个PersonTest.java测试类测试:
package com.jektong.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class PersonTest {
public static void main(String[] args) {
// 加载配置文件,此文件放在类路径下。
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
// 获取bean.xml文件中注入的Person对象,并输出。
Person bean = (Person) applicationContext.getBean("person");
System.out.println(bean);
}
}
输出结果如下:
注解Spring开发
舍弃上面的bean.xml文件,通过注解的方式将xml文件转换成配置类,建立PersonConfig配置类:
package com.jektong.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.jektong.spring.Person;
@Configuration // 告诉spring这是配置类相当于配置文件bean.xml
public class PersonConfig {
// 这是注入到spring容器的对象ID
// 括号内指定唯一ID,不指定则是默认以方法名为唯一ID,相当于:标签中的ID值。
@Bean("person01")
public Person person() {
return new Person("李四",21);
}
}
测试使用AnnotationConfigApplicationContext类读取注解:
package com.jektong.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.jektong.config.PersonConfig;
public class PersonTest {
public static void main(String[] args) {
ApplicationContext ac = new AnnotationConfigApplicationContext(PersonConfig.class);
Person bean = ac.getBean(Person.class);
System.out.println(bean);
// 查看BEAN的id
String[] beanDefinitionNames = ac.getBeanNamesForType(Person.class);
for (int i = 0; i
输出如下:
@Configuration与@Bean作用总结
@Configuration
相当于spring中的XML配置文件,将此XML文件替代成配置类,声明在类上。
@Bean
相当于XML文件中所配置的各个Bean对象,现声明在方法上,默认以方法名作为注入的Bean的id。
相关文章
- 逃离鸭科夫结局有几个 结局0和结局1达成条件一览 12-16
- 学信网官网登录入口-高等教育学历查询官方通道 12-16
- 失控进化预约入口官网 预约地址及预约奖励一览 12-16
- 网页版邮箱登录入口全攻略及实用技巧大全 12-16
- 学习通网页版访问线路升级-一键直达课程界面更快捷 12-16
- 光与影33号远征队持久强力符文:符文持久强力的作用及获取方式详解 12-16

