1. 导包 4+2+1
aop
2. 导入约束文件
xmlns:context="http://www.springframework.org/schema/context" |
http://www.springframework.org/schema/context |
3. 指定扫描的包
<!--指定扫描的位置,自动扫描该包以及该包所有的子包--> <context:component-scan base-package="cn.hd.annotation"></context:component-scan>
4. 为类声明注解
在类上书写代码
@Component("user") //@Controller("user")//web层 //为了解决所有的bean都是同一个注解,导致层次不清淅,提出了三个新的注解 public class User { 相当于在.xml bean name=user class=cn.hd.annotationUser } |
没有强制要求,都可以用,提倡按照他的本意去注解
修改Scope属性
@Scope(scopeName = "prototype") singleton|prototype 单例(默认)和多例 |
属性注入:
(1) 值类型: 注解写在属性上面,同时也可以写在set方法上面
@Value("张三") |
(2) 引用类型:
// @Autowired //自动装配 如果只有一个对象 自动装配 private Car car; |
(3) 创建对象后就执行的方法
@PostConstruct |
Spring结合junit
1. 导包
test
2. 书写测试代码
@RunWith(SpringJUnit4ClassRunner.class)//结合junit测试 |
由于原来使用的是application对象,读取配置和获得bean对象
但是现在没有了 又想获得对象
@Resource(name="user") |