文章目录
1.spring 的bean管理(注解)
注解介绍
1.代码里面特殊标记,使用注解可以完成功能
2.注解写法 @注解名称(属性名称=属性值)
3.注解使用在类上面,方法上面和属性上面
准备工作
applications.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">
<!--- 开启注解扫描
(1)到包里面扫描类,方法,属性上面是否有注解
-->
<context:component-scan base-package="studyDay2"/>
<!---
扫描属性上面的注解
-->
<!-- <context:annotation-config></context:annotation-config>-->
</beans>
使用注解创建对象
1.在创建对象的类上面使用注解实现
package studyDay2.anno;
import org.springframework.stereotype.Component;
@Component(value = "user") //等价于<bean id="user" class""/>
public class User {
}
测试代码:
ApplicationContext context =
new ClassPathXmlApplicationContext("applications.xml");
User user = (User) context.getBean("user");
System.out.println(user);
user.add();
2.创建对象有4个注解
- @Component:仅仅表示一个组件(Bean)
- @Controller:WEB层
- @Service:业务层
- @Repository:持久层
3.创建对象单实例还是多实例
@Scope(value = "prototype")
public class User {
}
注解注入属性
1.创建 service 类,创建 dao 类,在 service 得到 dao 对象
注入属性第一个注解 @Autowired
(1)创建 dao 和 service 对象
@Service("userService")
public class UserService {
}
@Component("userDao")
public class UserDao {
}
(2)在service 类里面定义 dao 类型属性
//得到 dao 对象
//1.定义 dao 类型属性
//在 dao 属性上面使用注解完成对象注入
@Autowired
private UserDao userDao;
//使用注解时不需要 set 方法
测试代码:
ApplicationContext context =
new ClassPathXmlApplicationContext("applications.xml");
UserService userService = (UserService) context.getBean("userService");
System.out.println(userService);
userService.add(</