spring framework Annotation(注解)
spring framework (4.2.4)Annotation(注解)
1、建立java项目
所用JAR
commons-logging-1.1.3.jar
spring-aop-4.2.4.RELEASE.jar
spring-beans-4.2.4.RELEASE.jar
spring-context-4.2.4.RELEASE.jar
spring-core-4.2.4.RELEASE.jar
spring-expression-4.2.4.RELEASE.jar
2、创建bean.xml放在项目src目录下
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans 3 xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xmlns:context="http://www.springframework.org/schema/context" <!-- 需手动添加 --> 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 8 http://www.springframework.org/schema/context <!-- 需手动添加 --> 9 http://www.springframework.org/schema/context/spring-context-3.0.xsd" <!-- 需手动添加 --> 10 > 11 <!-- 配置扫描说有的com下所有的包以及子包 --> 12 <context:component-scan base-package="com"/> 13 </beans>
2、建立JAVA实体类
Student类
1 package com.entity; 2 3 import javax.annotation.Resource; 4 5 import org.springframework.beans.factory.annotation.Value; 6 import org.springframework.stereotype.Component; 7 8 @Component("student") 9 public class Student { 10 @Value("20160125") 11 private int id; 12 @Value("张三") 13 private String name; 14 @Resource(name="myDate") 15 private MyDate date; 16 public int getId() { 17 return id; 18 } 19 public void setId(int id) { 20 this.id = id; 21 } 22 public String getName() { 23 return name; 24 } 25 public void setName(String name) { 26 this.name = name; 27 } 28 public MyDate getDate() { 29 return date; 30 } 31 public void setDate(MyDate date) { 32 this.date = date; 33 } 34 35 @PostConstruct//初始化方法 36 //@PreDestory销毁 37 public void abc() { 38 System.out.println("abc()"); 39 } 40 41 }
MyDate类
1 package com.entity; 2 3 import java.util.Date; 4 5 import org.springframework.stereotype.Service; 6 7 //@Component 8 @Service 9 public class MyDate extends Date { 10 11 }
3、Test类
1 package com.tese; 2 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 import com.entity.Student; 6 7 public class Test { 8 public static void main(String[] args) { 9 ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml"); 10 11 Student stu = (Student)ctx.getBean("student"); 12 System.out.println(stu.getId()); 13 System.out.println(stu.getName()); 14 System.out.println(stu.getDate()); 15 } 16 }
运行结果:
20160125
张三
Mon Jan 25 14:34:07 CST 2016
本文仅为个人学习笔记,如有错误请给予指点,谢谢!!!