spring5入门(九):基于注解管理bean,创建对象
- 注解简介
注解是代码特殊标记,格式:@注解名称(属性名称=属性值, 属性名称=属性值..)
使用注解,注解作用在类上面,方法上面,属性上面
使用注解目的:简化 xml 配置
- 有关bean的注解
@Component
@Service
@Controller
@Repository
-
使用注解创建对象
-
添加依赖
-
开启组件扫描
<?xml version="1.0" encoding="UTF-8"?>
创建bean,如果不指定value,默认时类名的首字母小写
@Component(value = "userService")
public class UserService {
public void add() {
System.out.println("service add.......");
}
}
- 测试方法
public class Test3 {
@Test
public void testAdd() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean7.xml");
UserService userService = context.getBean("userService", UserService.class);
System.out.println(userService);
userService.add();
}
}
- 控制台
com.ychen.spring.ser.UserService@452e19ca
service add.......
Process finished with exit code 0
组件扫描详情