依赖注入方式:
1.构造器注入
2.setter注入
3.接口注入
maven pom.xml配置
引入jar包和依赖jar
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.2.RELEASE</version>
</dependency>
</dependencies>
一定要保持版本一样,不然后面注解注入@Component会报错
配置spring-cfg.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">
</beans>
1.构造器注入
public class Role {
private Long id;
private String roleName;
private String note;
public Role(){
}
public Role(Long id, String roleName, String note) {
this.id = id;
this.roleName = roleName;
this.note = note;
}
public Long getId() {
return id;
}
public String getRoleName() {
return roleName;
}
public String getNote() {
return note;
}
public void setId(Long id) {
this.id = id;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public void setNote(String note) {
this.note = note;
}
}
<bean id="role_3" class="Chapter10.pojo.Role">
<constructor-arg index="0" value="1"/>
<constructor-arg index="1" value="总经理"/>
<constructor-arg index="2" value="公司管理者"/>
</bean>
2.setter注入
<bean id="role_1" class="Chapter10.pojo.Role">
//id为对象别名 class为定义的实体类位置
<property name="id" value="1"/>
<property name="note" value="note_1"/>
<property name="roleName" value="role_name_1"/>
</bean>
3.接口注入