spring两种从ioc容器中获取bean实例的方法.juint,@test
两种区别仅在junit测试
插播:junit和@test
@Test的使用 是该方法可以不用main方法调用就可以测试出运行结果,是一种测试方法
一般函数都需要有main方法调用才能执行,注意被测试的方法必须是public修饰的
JUnit是一个Java语言的单元测试框架。它由Kent Beck和Erich Gamma建立,逐渐成为源于Kent Beck的sUnit的xUnit家族中最为成功的一个。 JUnit有它自己的JUnit扩展生态圈。多数Java的开发环境都已经集成了JUnit作为单元测试的工具。
步骤1:写一个java类
package person;
public class person01 {
private String lastname;
private int aage;
private String email;
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int getAage() {
return aage;
}
public void setAage(int aage) {
this.aage = aage;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "person01 [lastname=" + lastname + ", aage=" + aage + ", email=" + email + "]";
}
}

步骤二:写springxml文件进行注册实例并赋值
<?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="per01" class="person.person01">
<property name="aage" value="18"></property></bean> -->
<!-- perxon02 -->
<bean id="per02" class="person.person01">
<property name="aage" value="18"></property>
<property name="email" value="17695455099@163.com"></property>
</bean>
<!-- csdn -->
</beans>

步骤三:写测试test使用juint4测试两种方法
package persontest;
import static org.junit.Assert.*;
import org.junit.Assert.*;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import person.person01;
public class testioc {
private ApplicationContext ioc=new ClassPathXmlApplicationContext("hellospring01.xml");
/* 通过类名获取bean实例*/
@Test
public void test02()
{
person01 bean = ioc.getBean(person01.class);
System.out.print(bean);
}
@Test
/* 通过id获取bean实例*/
public void test() {
//fail("Not yet implemented");
ApplicationContext ioc=new ClassPathXmlApplicationContext("hellospring01.xml");
person01 bean = (person01) ioc.getBean("per02");
System.out.print(bean);
}
}

uiui干啥的忘了(好像没用)
本文介绍如何在Spring框架中使用IoC容器获取Bean实例的两种方法:通过类名和通过Bean ID。同时,提供了详细的步骤和示例代码,包括创建Java类、配置XML文件以及使用JUnit进行测试。
2299

被折叠的 条评论
为什么被折叠?



