Spring简单练习

参考学习网站:https://how2j.cn/k/spring/spring-annotation-test/1133.html

一、认识Spring

Spring是一个基于IOC和AOP的结构J2EE系统的框架
IOC 反转控制 是Spring的基础,Inversion Of Control
简单说就是创建对象由以前的程序员自己new 构造方法来调用,变成了交由Spring创建对象
DI 依赖注入 Dependency Inject. 简单地说就是拿到的对象的属性,已经被注入好相关值了,直接使用即可

二、实例1(创建对象)

0创建项目

1导入jar包

在这里插入图片描述

创建一个实体类

package com.how2java.pojo;

public class Category {
	
	private int id;
	private String name;
	//省略getting和setting
	}

编写核心配置类applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/context     
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  
    <bean name="c" class="com.how2java.pojo.Category">
        <property name="name" value="category 1" />
    </bean>
  
</beans>

其中,

<bean 表示配置需要创建的对象,name="c"通过关键字c即可获取Category对象,class需要创建实例的全限定类名。

< property name=“name” value=“category 1” />即被注入了字符串"category 1“到name属性中

创建测试类TestSpring

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类的。下面创建一个product对象并且注入category对象。

0添加product类

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;
	}
}

1修改xml

	<bean name="p" class="com.how2java.pojo.Product">
        <property name="name" value="product1" />
        <property name="category" ref="c" />
    </bean>

2测试

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

这样就实现了创建一个product类的同时注入一个实例化的category对象

==========================================================================================================================

用注解方式完成以上例子

用到的注解有:

@Component注解,即表明此类是bean
@Autowired注解(还可以在setting方法中使用这个注解,
除此之外还可以用@Resource(name="c")注解需要注入的对象)

然后xml文件中只需写< context:component-scan base-package=“com.how2java.pojo”/>

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/context     
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  
    <context:component-scan base-package="com.how2java.pojo"/>
     
</beans>

另外,因为配置从applicationContext.xml中移出来了,所以属性初始化放在属性声明上进行了。

package com.how2java.pojo;
 
import javax.annotation.Resource;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
@Component("p")
public class Product {
 
    private int id;
    private String name="product 1";
     
    @Autowired
    private Category category;
 
    //省略getting和setting
}

==========================================================================================================================

四、AOP(面向切面编程)

AOP 即 Aspect Oriented Program 面向切面编程
首先,在面向切面编程的思想里面,把功能分为核心业务功能,和周边功能。
所谓的核心业务,比如登陆,增加数据,删除数据都叫核心业务
所谓的周边功能,比如性能统计,日志,事务管理等等

周边功能在Spring的面向切面编程AOP思想里,即被定义为切面

在面向切面编程AOP的思想里面,核心业务功能和切面功能分别独立进行开发
然后把切面功能和核心业务功能 “编织” 在一起,这就叫AOP

五、思路图

  1. 功能分两大类,辅助功能和核心业务功能
  2. 辅助功能和核心业务功能彼此独立进行开发
  3. 比如登陆功能,即便是没有性能统计和日志输出,也可以正常运行
  4. 如果有需要,就把"日志输出" 功能和 “登陆” 功能 编织在一起,这样登陆的时候,就可以看到日志输出了
  5. 辅助功能,又叫做切面,这种能够选择性的,低耦合的把切面和核心业务功能结合在一起的编程思想,就叫做切面编程

在这里插入图片描述

六、实例3

0创建业务类ProductService

public class ProductService {
	public void doSomeService() {
		System.out.println("dosomeservice");
	}
}

1在引入切面之前,调用该业务类

public class TestSpring {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
        ProductService s = (ProductService) context.getBean("s");
        s.doSomeService();
    }
}

2准备日志切面 LoggerAspect

该日志切面的功能是 在调用核心功能之前和之后分别打印日志,切面就是原理图中讲的那些辅助功能。

package com.how2java.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
 
public class LoggerAspect {
 
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("start log:" + joinPoint.getSignature().getName());
        Object object = joinPoint.proceed();
        System.out.println("end log:" + joinPoint.getSignature().getName());
        return object;
    }
}

3修改XML

添加以下内容

<bean name="s" class="com.how2java.service.ProductService">
    </bean>   
     
    <bean id="loggerAspect" class="com.how2java.aspect.LoggerAspect"/>
     
    <aop:config>
        <aop:pointcut id="loggerCutpoint"
            expression=
            "execution(* com.how2java.service.ProductService.*(..)) "/>
             
        <aop:aspect id="logAspect" ref="loggerAspect">
            <aop:around pointcut-ref="loggerCutpoint" method="log"/>
        </aop:aspect>
    </aop:config> 

4运行结果

在这里插入图片描述

==========================================================================================================================

七、把XML方式配置AOP 改造为注解方式

用到的注解

@Aspect 注解表示这是一个切面
@Component 表示这是一个bean,由Spring进行管理
@Around(value = "execution(* com.how2java.service.ProductService.*(..))") 表示对com.how2java.service.ProductService 这个类中的所有方法进行切面操作

ProductService类

@Component("s")
public class ProductService {

	public void doSomeService() {
		System.out.println("dosomeservice");
	}
}

LoggerAspect类

@Aspect
@Component
public class LoggerAspect {
	
	@Around(value="execution(* com.how2java.service.ProductService.*(..))")
	public Object log(ProceedingJoinPoint joinPoint) throws Throwable{
		
		System.out.println("start log:"+joinPoint.getSignature().getName());
		Object object =joinPoint.proceed();
		System.out.println("end log:"+joinPoint.getSignature().getName());
		return object;
	}
}

xml修改

<context:component-scan base-package="com.how2java.aspect"/>
<context:component-scan base-package="com.how2java.service"/>
<aop:aspectj-autoproxy/>

运行结果
在这里插入图片描述

八、注解方法测试

导入jar包

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

}

  1. @RunWith(SpringJUnit4ClassRunner.class)
    表示这是一个Spring的测试类

  2. @ContextConfiguration(“classpath:applicationContext.xml”)
    定位Spring的配置文件

  3. @Autowired
    给这个测试类装配Category对象

  4. @Test
    测试逻辑,打印c对象的名称

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值