Spring中@Bean注解如何使用?
摘要:@Bean 作用: 该注解只能写在方法上,表明使用此方法创建一个对象,并且放入spring容器。 🌟 青柠来相伴,代码更简单。🌟 📚 本文所有内
@Bean
作用:
该注解只能写在方法上,表明使用此方法创建一个对象,并且放入spring容器。
====== 🌟 青柠来相伴,代码更简单。🌟 ======
📚 本文所有内容,我都整理成了文档资料。👇
🎯 搜索【青柠代码录】,关键字:青柠合集
🚀 即可查看所有博客文章 ~
====== 🌟 ================= 🌟 ======
属性:
name:给当前@Bean注解方法创建的对象,指定一个名称(即bean的id)。
/**
* 连接数据库的配置类
*/
public class JdbcConfig {
/**
* 创建一个数据源,并存入spring容器中
* @return
*/
@Bean(name = "dataSource")
public DataSource createDataSource() {
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setUser("root");
ds.setPassword("1234");
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql:///spring_day02");
return ds;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 创建一个DBAssit,并且也存入spring容器中
* @param dataSource
* @return
*/
@Bean(name = "dbAssit")
public DBAssit createDBAssit(DataSource dataSource) {
return new DBAssit(dataSource);
}
}
通过XML配置文件注入JavaBean
创建一个Person类,作为测试的JavaBean
package com.meimeixia.bean;
public class Person {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Person(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
创建Spring的配置文件,例如beans.xml,通过该配置文件,将Person类注入到Spring的IOC容器中,该配置文件中的内容如下所示。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
<!-- 注册组件 -->
<bean id="person" class="com.meimeixia.bean.Person">
<property name="age" value="18"></property>
<property name="name" value="liayun"></property>
</bean>
</beans>
package com.meimeixia;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.meimeixia.bean.Person;
public class MainTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
Person person = (Person) applicationContext.getBean("person");
System.out.println(person);
}
}
从输出结果中,我们可以看出,Person类通过beans.xml文件的配置,已经注入到Spring的IOC容器中去了。
通过注解注入JavaBean
@Bean注解是给IOC容器中注册一个bean,类型自然就是返回值的类型,id默认是用方法名作为id
名称(Name): 是用来在Spring容器中,唯一标识和查找bean的字符串标识符。通常由方法名决定,也可以显式指定。在Spring中,每个bean都有一个唯一的名称,这个名称通常是用来在容器中、查找和获取特定的bean实例。
类型(Type): 是指bean的Java类类型。由 @Bean 方法的返回类型确定。
创建一个MainConfig类,并在该类上添加@Configuration注解,来标注该类是一个Spring的配置类,也就是告诉Spring它是一个配置类,配置类就相当于一个xml文件,最后通过@Bean注解,将Person类注入到Spring的IOC容器中。
package com.meimeixia.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.meimeixia.bean.Person;
/**
* 以前配置文件的方式被替换成了配置类,即配置类==配置文件
*/
// 这个配置类也是一个组件
@Configuration // 告诉Spring这是一个配置类
public class MainConfig {
@Bean
public Person person() {
return new Person("liayun", 20);
}
}
主要是我们在类上加上@Configuration注解,并在方法上加上@Bean注解,就能够将方法中创建的JavaBean,注入到Spring的IOC容器中。
然后,修改MainTest类中的main方法,以测试通过注解注入的Person类,如下所示。
package com.meimeixia;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.meimeixia.bean.Person;
import com.meimeixia.config.MainConfig;
public class MainTest {
public static void main(String[] args) {
// ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
// Person person = (Person) applicationContext.getBean("person");
// System.out.println(person);
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Person person = applicationContext.getBean(Person.class);
System.out.println(person);
}
}
使用注解将JavaBean注入到IOC容器中时,使用的bean的名称又是什么呢?
我们可以在MainTest类的main方法中,添加如下代码,来获取Person这个类型的组件,在IOC容器中的名字。
// Person这个类型的组件在IOC容器中的名字是什么呢?
String[] namesForType = applicationContext.getBeanNamesForType(Person.class);
for (String name : namesForType) {
System.out.println(name);
}
