加入依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.22</version>
</dependency>
</dependencies>
创建一个实体类Person
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {
private String name;
private String age;
}
第一种:用xml配置文件的方式
创建一个spring xml的文件命名为bean.xml
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person" class="com.spring.bean.Person">
<property name="age" value="20"></property>
<property name="name" value="小杨"></property>
</bean>
</beans>
在main方法中进行测ing
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
//可以是id,也可以是类的class对象
//Object person = context.getBean("person");
Person person = context.getBean(Person.class);
System.out.println(person);
控制台输出:
第二种:配置类的方式
创建一个配置类
@Configuration //告诉spring这是个配置类
public class SpringConfig {
/**
* 给spring ioc中注册一个bean,返回值即为类型,方法名即为id
* 将方法返回值注入到容器中
*/
@Bean(value = "per") //也可定义别名id,不加value值则默认方法名为id
public Person personTest(){
return new Person("小陈","22");
}
}
main方法测试
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
// Object person = context.getBean("personTest");
Person person = context.getBean(Person.class);
System.out.println(person);
//获取id
String[] beanNamesForType = context.getBeanNamesForType(Person.class);
for (String bean: beanNamesForType){
System.out.println(bean);
}
}
控制台输出: