使用注解配置spring

  • 在配置文件开启注解
<!-- 指定扫描com.gjh.bean包下的所有类中的注解
    注意:扫描包时会扫描指定包下的所有子孙包
-->
<context:component-scan base-package="com.gjh.bean" />
  • 在实体类上声明注解
@Component("person")
public class Person{

}
@Repository("person")
public class Person{

}

spring早期注解使用@Component.实例化对象,但到后期为了区分每层的作用又延伸出@Service(service层) @Controller(web层) @Repository(dao层) 作用其实和@Component一样,如果注解中的属性只有一个属性需要赋值并且是value 可以省略

  • 修改对象的作用范围
@Repository("person")
@Scope(scopeName="prototype"public class Person{

}
  • 值类型注入
@Repository("person")
@Scope(scopeName="prototype"public class Person{
@Value("gjh")
private String name;//通过反射的Field赋值,破坏了封装性
}
@Repository("person")
@Scope(scopeName="prototype"public class Person{
private String name;
@Value("gjh")
public void setName(String name){
//通过set方法注入,推荐使用
    this.name=name;
}
}
  • 引用类型注入
@Repository("person")
@Scope(scopeName="prototype"public class Person{
@Autowired //自动装配
private Car car;
}
@Repository("person")
@Scope(scopeName="prototype"public class Person{
@Autowired //自动装配
如果有多个Car的实例(实例名字不同),将无法选择具体注入哪一对象
@Qualifier("car2") //使用@Qualifilter注解告诉spring容器自动装配那个名称的对象
private Car car;
}
@Repository("person")
@Scope(scopeName="prototype"public class Person{
@Resource(name="car"//手动注入,指定注入哪个名称的对象
private Car car;
}
  • 初始化&销毁方法
```java
@Repository("person")
@Scope(scopeName="prototype"public class Person{
@PreDestroy //在对象销毁之前调用(对应配置文件中的destroy-methond)
public void init(){
    }
@PostConstruct //在对象创建后调用(对应配置文件中的init-methond)
public void destroy(){

    }
}

spring整合junit测试

//帮我们创建容器
@RunWith(SpringJUnit4ClassRunner.class)
//制定创建容器时使用哪个配置文件
@ContextConfiguration("classpath:applicationContext.xml")
public class Tets{
//将名为user的对象注入到u变量中
@Resource(name="user")
private User u;
@Test
public void fun(){
System.out.println(u);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值