- 在配置文件开启注解
<!-- 指定扫描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);
}
}