Article Directory
Compare with the previous one: https://blog.csdn.net/weixin_42556863/article/details/108952582 .
Preface
Used xml to build the project
Tip: The following is the content of this article, the following cases are for reference
1. What is xml? (All code writers don’t like to read the text description)
XML is a markup language used to mark electronic files to make them structured.
Second, use steps
Precondition
Need to create a class and an interface respectively:
//SomeService.java
public interface SomeService {
void doSome();
}
//SomeServiceImpl.java
public class SomeServiceImpl implements SomeService {
@Override
public void doSome() {
System.out.println("执行了SomeServiceImpl中的doSome方法");
}
}
1. Create the beans.xml file in the resource (right-click resource–>New–>XML Configuration File -->Spring Config)
2. Write beans.xml
The role of beans.xml:
tell spring to create an object.
Declaring a bean is to tell spring the object
id of a certain class to be created : the custom name and unique value of the object. Spring finds the object
class by name : the fully qualified name of the class (it cannot be an interface, because spring is a reflection mechanism to create objects, you must use the class) spring is done SomeService service1=new SomeServiceImpl();
spring is to place the created object in the map , There is a map to store objects in spring.
springMap.put (value of id, object);
For example: springMap.put("someService",new SomeServiceImpl());
A bean declares an object.
<bean id="someService" class="com.kekek.service.impl.SomeServiceImpl" />
3. Write test cases
String name: names is an enumeration of foreach,
in fact
for (String name:names) {
System.out.println("容器中定义的对象名称:"+name);
}
Equivalent to
for (int i = 0; i < names.length ; i++) {
System.out.println("容器中定义的对象名称:"+names[i]);
}
Complete code
@Test
public void test03(){
//编写xml的名称
String config="beans.xml";
ApplicationContext ac=new ClassPathXmlApplicationContext(config);
//使用spring提供的方法,获取容器中定义的对象的数量
int nums=ac.getBeanDefinitionCount();
System.out.println("容器中定义的对象数量:"+nums);
//容器中每个定义的对象的名称
String names [] = ac.getBeanDefinitionNames();
for (String name:names) {
System.out.println("容器中定义的对象名称:"+name);
}
}
operation result
There is only one bean in beans.xml, and the name is someService