Spring学习笔记

目录

1.XML方式使用Spring
2.注解方式使用Spring
3.注解方式测试


一、XML方式使用Spring

1. IOC/DI

使用Spring共分为四个步骤:导包、创建实体类、配置applicationContext.xml、应用。
(1)导包
(2)创建实体类

package com.how2java.pojo;
 
public class Category {
 
    private int id;
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

(3)配置applicationContext.xml,放在src目录下



  
    
        
    
  

(4)应用

package com.how2java.test;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.how2java.pojo.Category;
 
public class TestSpring {
 
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
 
        Category c = (Category) context.getBean("c");
         
        System.out.println(c.getName());
    }
}

2.注入对象

要在product对象中注入一个category对象,步骤如下。
(1)创建实体类category

package com.how2java.pojo;
 
public class Product {
 
    private int id;
    private String name;
    private Category category;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Category getCategory() {
        return category;
    }
    public void setCategory(Category category) {
        this.category = category;
    }
}

(2)在applicationContext.xml中的product这个bean里加上如下代码。

        

(3)在应用类里可以测试,可以看出category已经被注入到product中。

        Product p = (Product) context.getBean("p");
        System.out.println(p.getCategory().getName());

3.AOP(面向切面编程)

(1)创建业务类ProductService,它里面有一些辅助功能。
(2)准备日志切面LoggerAspect。
(3)配置applicationContext.xml
(4)应用


二、注解方式使用Spring

1.注解方式IOC/DI

(1) 修改applicationContext.xml
添加下面代码,表示要用的bean都在pojo包里。同时去掉原来的bean代码。

    

(2)修改实体类文件
首先要在实体类的类名上面加上@Component("XXX")

@Component("p")
public class Product {

其次在要注入的对象这个属性上面加@Autowired

    @Autowired
    private Category category;

最后把属性初始化放在属性声明上进行

    private String name="product 1";

2.注解方式AOP

首先注解配置业务类,这个跟配置实体类一样

@Component("s")
public class ProductService {

然后配置切面

@Aspect
@Component
public class LoggerAspect { 
     
    @Around(value = "execution(* com.how2java.service.ProductService.*(..))")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {

最后记得写applicationContext.xml

    
    
      

三、注解方式测试

(1)导包:junit-4.12.jar和hamcrest-all-1.3.jar
(2)在应用类中添加注解

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestSpring {
    @Autowired
    Category c;
 
    @Test
    public void test(){
        System.out.println(c.getName());
    }

你可能感兴趣的:(Spring学习笔记)