赞
赏
使用基于注解配置的 Spring IOC 创建对象,使用 @Autowired 注入数据。
搭建 Spring 的开发环境,使用基于注解配置的 Spring IOC 创建对象,使用 @Autowired 注入数据。
pom 文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.haicoder</groupId>
<artifactId>SpringDemo08</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--IOC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
</dependencies>
</project>
核心配置文件:
<?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 http://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="net.haicoder"/>
<!--属性值-->
<bean id="id" class="java.lang.Integer">
<constructor-arg index="0" value="1"/>
</bean>
<bean id="name" class="java.lang.String">
<constructor-arg index="0" value="HaiCoder"/>
</bean>
</beans>
实体类:
@Component
public class User {
private Integer id;
private String name;
@Autowired
public User(Integer id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
测试类:
public class DemoTest {
public static void main(String[] args) {
System.out.println("嗨客网(www.haicoder.net)\n");
// IOC容器
ApplicationContext act = new ClassPathXmlApplicationContext("applicationContext.xml");
// 获取对象
User user = (User) act.getBean("user");
System.out.println(user);
}
}
运行结果如下:
以上案例使用基于注解配置的 Spring IOC 创建对象,并使用 @Autowired 注入数据。