在使用XML配置文件时可以将一个bean引用到另一个bean中,例如以下代码:
<bean id = "source" class="com.ssm.spring.pojo.Source">
<property name="fruit" value="橙汁"/>
<property name="size" value="大杯"/>
<property name="sugar" value="半糖"/>
</bean>
<bean id = "juiceMaker" class = "com.ssm.spring.pojo.JuiceMaker" init-method="init" destroy-method="myDestroy">
<property name="beverageShop" value="茶百道"/>
<property name="source" ref="source"/>
</bean>
上述代码中juiceMaker这个bean的source属性引用了id=source的bean。
在注解中可以自动发现对应的bean并自动完成装配。
@Autowired注解可以实现自动装配Ioc中的bean
案例:
(1)定义接口RoleService
package com.ssm.spring.annotation.service;
public interface RoleService {
public void printRoleInfo();
}
(2)类RoleServiceImpl实现接口
@Component说明RoleServiceImpl需要装入Ioc容器中
@Autowired用于自动装配,spring会将Ioc容器中的Role自动装入RoleServiceImpl中
package com.ssm.spring.annotation.service.impl;
import com.ssm.spring.annotation.pojo.Role;
import com.ssm.spring.annotation.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component("RoleService")
public class RoleServiceImpl implements RoleService {
@Autowired
private Role role = null;
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
@Override
public void printRoleInfo() {
System.out.println("id ="+role.getId());
System.out.println("roleName ="+role.getRoleName());
System.out.println("note ="+role.getNote());
}
}
(3)定义类Role
@Component表明Role需要被装入Ioc容器中 @Value给成员变量设置值。
package com.ssm.spring.annotation.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component(value = "role")
public class Role {
@Value("1")
private Long id;
@Value("role_name_1")
private String roleName;
@Value("role_note_1")
private String note;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", roleName='" + roleName + '\'' +
", note='" + note + '\'' +
'}';
}
}
(4)实现java config类,用于spring扫描对应的包,这样才能将要加入Ioc容器中的bean加入进去
package com.ssm.spring.annotation.config;
import com.ssm.spring.annotation.pojo.Role;
import com.ssm.spring.annotation.service.impl.RoleServiceImpl;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackageClasses = {Role.class, RoleServiceImpl.class})
public class ApplicationConfig {
}
(5)编写测试代码
在测试代码中只获取RoleServiceImpl的bean,没有获取Role,因为Role已经自动注入RoleServiceImpl中了。
@Test
public void test1()
{
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);
RoleService service = context.getBean(RoleService.class);
service.printRoleInfo();
context.close();
}
运行结果;
运行成功。