一、使用@Configuration 和@Bean给容器中注册组件;
1、创建一个Maven工程,导入Spring的依赖
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
使用配置文件测试;
先创建一个Person的类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
private String name;
private int age;
}
紧接着,在工程的src/main/resources目录下创建Spring的配置文件,例如beans.xml,通过该配置文件将Person类注入到Spring的IOC容器中,该配置文件中的内容如下所示。
<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person" class="com.baidu.pojo.Person">
<property name="name" value="zhangsan"/>
<property name="age" value="12"/>
</bean>
</beans>
至此,我们使用XML配置文件的方式注入JavaBean就完成了。
接下来,在工程的test包下进行测试;创建MyTest测试类
public class MyTest {
@Test
public void Person(){
//配置bean开发
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
Person person = context.getBean("person", Person.class);
System.out.println(person);
}
}
使用注解测试:
新创建一个MyConfig的类,给类上添加注解
@Configuration //告诉Spring这是一个配置类,相当于Bean.xml
public class MyConfig {
@Bean("person01") //相当于我们的bean
public Person person(){
return new Person("lisi",20);
}
}
测试:
@Test
public void Person(){
// //配置bean开发
// ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
// Person person = context.getBean("person", Person.class);
// System.out.println(person);
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
Person bean = context.getBean(Person.class);
System.out.println(bean);
//根据类型获取到bean的名字;
String[] beanNames = context.getBeanNamesForType(Person.class);
for (String name : beanNames) {
System.out.println(name);
}
}
小结
在类上添加@Configuration注解来标注该类是一个Spring的配置类,也就是告诉Spring它是一个配置类,最后通过@Bean注解将Person类注入到Spring的IOC容器中
我们在使用注解方式向Spring的IOC容器中注入JavaBean时,如果没有在@Bean注解中明确指定bean的名称,那么就会使用当前方法的名称来作为bean的名称;如果在@Bean注解中明确指定了bean的名称,那么就会使用@Bean注解中指定的名称来作为bean的名称。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/71826.html