Spring注解配置初始化对象(<bean>)

Spring注解配置初始化对象(<bean>):

spring中使用注解配置对象前,要在配置文件中配置context:component-scan 标签

告诉spring框架,配置了注解的类的位置

配置文件applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd ">

<!-- 扫描cn.example.bean包和其所有子孙包中所有类中的注解. -->

<context:component-scan base-package="cn.example.bean"></context:component-scan>

</beans>

 

Javabean类:

@Repository("user")//该注解,等同于配置文件的bean,spring初始化时,就会创建该对象

@Scope(scopeName="singleton"//等同于配置文件的scope属性

public class User {

//注解赋值,直接在成本变量上注解是通过反射field赋值,只赋值value一个属性时,value可以省略

@Value(value="188")

private Integer age;

//给对象赋值,该值car必须要已经声明(在配置文件中已经配置,或者在类对应中已经注解)

@Resource(name="car"

private Car car;

public Car getCar() {

return car;

}

public void setCar(Car car) {

this.car = car;

}

public String getName() {

return name;

}

@Value("tom") //注解赋值  通过调用set方法赋值

public void setName(String name) {

this.name = name;

}

public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

@PostConstruct //指定该方法在对象被创建后马上调用 相当于配置文件中的init-method属性

public void init(){

System.out.println("我是初始化方法!");

}

@PreDestroy //指定该方法在对象销毁之前调用 相当于配置文件中的destory-method属性

public void destory(){

System.out.println("我是销毁方法!");

}

@Override

public String toString() {

return "User [name=" + name + ", age=" + age + ", car=" + car + "]";

}

}

@Component("car")

public class Car {

@Value("小青")

private String  name;

@Value("绿")

private String color;

public String getName() {return name;}

public void setName(String name) {this.name = name;}

public String getColor() {return color;}

public void setColor(String color) {this.color = color;}

}

注解说明:

Component最初spring框架设计的,后来为了标识不同代码层,衍生出Controller,Service,Repository三个注解 作用相当于配置文件的bean标签被注解的类,spring始化时,就会创建该对象

@Component("user")  给类注解

@Service("user") // service层

@Controller("user") // web业务

@Repository("user")//dao

 

@Scope(scopeName="singleton") 等同于配置文件的scope属性

@Value(value="188") //给值属性赋值,可以用在方法上或者属性上

@Resource(name="car"//给对象赋值,该值car必须要已经声明(在配置文件中已经配置,或者在类对应中已经注解)

@PostConstruct //指定该方法在对象被创建后马上调用 相当于配置文件中的init-method属性

@PreDestroy //指定该方法在对象销毁之前调用 相当于配置文件中的destory-method属性

@Autowired //自动装配对象赋值+@Qualifier("car2") 一起使用 告诉spring容器自动装配哪个对象

 

猜你喜欢

转载自blog.csdn.net/u011266694/article/details/78918382