1.xml文件配置
(1) 定义要扫描的包 package=“com.qq.test4”
(2) 开启注解:context:annotation-config/
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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.qq.test4"/>
<context:annotation-config/>
</beans>
- 标记注解
package com.qq.test4.dao;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class UserDao {
@Value("user1")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3.测试
@org.junit.jupiter.api.Test
public void test4(){
//解析xml,获取Spring上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("bean5.xml");
UserDao userDao = context.getBean("userDao",UserDao.class);
System.out.println(userDao.getName());
}
输出为:
user1