使用注解配置spring


1. 导包 4+2+1

aop

 

2. 导入约束文件

xmlns:context="http://www.springframework.org/schema/context"

http://www.springframework.org/schema/context
http://www.springframework.org/schema/context.xsd

3. 指定扫描的包

<!--指定扫描的位置,自动扫描该包以及该包所有的子包-->
     <context:component-scan base-package="cn.hd.annotation"></context:component-scan>

4. 为类声明注解

 


在类上书写代码

@Component("user")

//@Controller("user")//web层
//
@Service("user") //service 层
//
@Repository("user")//dao层

//为了解决所有的bean都是同一个注解,导致层次不清淅,提出了三个新的注解

public class User { 相当于在.xml bean name=user class=cn.hd.annotationUser
    private String name;
    private Integer age;
    private String address;
    private Car car;

}

没有强制要求,都可以用,提倡按照他的本意去注解

 

修改Scope属性

@Scope(scopeName = "prototype") singleton|prototype 单例(默认)和多例

 

属性注入:

(1) 值类型: 注解写在属性上面,同时也可以写在set方法上面

@Value("张三")
private String name;
@Value("20")
private Integer age;
@Value("河南")
private String address;

(2) 引用类型:

// @Autowired //自动装配 如果只有一个对象  自动装配
//    @Qualifier("car2") //自动装配时有多个对象要指定那个对象,与自动装配结合使用
//    @Resource(name = "car")  //直接指定配置那个对象

private Car car;

(3) 创建对象后就执行的方法

@PostConstruct
public void init(){
    System.out.println("创建对象后自动执行");
}
@PreDestroy
public void destroy(){
    System.out.println("对象销毁前执行");
}

  

 

 

 

 

Spring结合junit

1. 导包

test


 

2. 书写测试代码

@RunWith(SpringJUnit4ClassRunner.class)//结合junit测试
@ContextConfiguration("classpath:cn/hd/annotation/applicationContext.xml") //读取配置文件

  由于原来使用的是application对象,读取配置和获得bean对象

  但是现在没有了 又想获得对象

@Resource(name="user")
private User user;

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值