Java 7.Spring--使用注解

1.创建web项目

2.引入jar包

 

 

 

 

3.日志文件

 

 

 

 

4.创建实体类

Person

Car

 

5.创建applicationContext.xml

<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 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
        
</beans>

 

6.配置注解扫描

指定要扫描的包

 

<context:component-scan base-package="com.spring.pojo"></context:component-scan>

 

 

 

7.在类中使用注解

 

@Component("person")
@Repository("person")
@Service("person")
@Controller("person")
//<bean name="person" class="com.Spring.pojo.Person"></bean>  相同

 

  

 

8.其他类级别的注释

 

 

@Component("person")     //适用于所有组件
@Repository("person")    //适用于持久层
@Service("person")    //适用于service
@Controller("person")  //适用于controller

9.指定对象的scope的属性

 

@Component("person")
@Scope(scopeName="singleton")

 

  

 

10.set方式注入value值

1-在私有的成员变量中注入

 

@Value("helen") ==@Value(value="helen")

 

 

	@Value("helen")
	private String name;
	@Value("18")
	private Integer age;

 

  

 

2-在set方法中注入

 

	@Value("tom")
	public void setName(String name) {
		this.name = name;
	}

 

  

 

11.自动装配

 

@Autowired  进行自动装配,按照对象类型进行自动装配

 

 

@Component("car")
public class Car {
	@Value("小黄车")
	private String name;
	@Value("蓝色")
	private String color;

 

  

 

 

public class Person {
	
	@Value("helen")
	private String name;
	@Value("18")
	private Integer age;
	@Autowired
	private Car car;

 

  

 

自动装配存在的问题:如果一个类型有多个对象,那么可以采取以下的方式

方法一:

使用指定@Qualifier指定具体的对象

 

	@Autowired
	@Qualifier("car2")
	private Car car;

 

  

 

方式二:

使用@Resource指定具体的对象

 

	@Resource(name="car1")
	private Car car;

 

  

 

12.初始化方法和销毁方法

 

	@PostConstruct   //初始化
	public void init() {
		System.out.println("Person被初始化了。。。");
	}
	@PreDestroy    //销毁
	public void destroy() {
		System.out.println("Person被摧毁了。。。");
	}

 

  

 

 

 

posted @ 2020-01-06 10:30  Recruited  阅读(208)  评论(0编辑  收藏  举报
个人网站:www.yuzhenfu.cn