PART_ONE:IOC
Spring的ioc可以解决开发过程中New对象的操作。
1.除了导入Spring的jar包还要导入之后aop需要的jar包
2.xml配置的方式
a.简单的User.class
package entiy;
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void showUser() {
System.out.println("i am a user");
}
}
b.Spring的核心配置文件,applicationContext.xml
c.获取User实例
@Test
public void test() {
//加载spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User test = (User) context.getBean("user");
test.showUser();
}
d.bean方式配置的时候,要注意User类中是否有无参构造函数
3.ioc的注解方式实现
a.在applicationContext.xml中加入注释的支持
b.测试类
dao
public interface PersonDao {
public void showName(Person person);
}
daoimp
package dao;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import entiy.Person;
@Repository
public class PersonDaoImpl implements PersonDao{
@Override
public void showName(Person person) {
System.out.println(person.getName());
}
}
service
package dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import entiy.Person;
@Service(value="personService")
public class PersonService {
@Autowired
private PersonDao personDao;
public void showName(Person person) {
personDao.showName(person);
}
}
test
@Test
public void testService() {
//加载spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService service = (UserService) context.getBean("userSerive");
User test = new User();
test.setName("handsomeboy");
service.showName(test);
}
c.四个注解的简单介绍
PART_TWO:AOP操作
AOP的四个概念
Joinpoint(连接点): 类里面可以被增强的方法,这些方法称为连接点
Pointcut(切入点):所谓切入点是指我们要对哪些Joinpoint进行拦截的定义.
Advice(通知/增强):所谓通知是指拦截到Joinpoint之后所要做的事情就是通知.通知分为前置通知,后置通知,异常通知,最终通知,环绕通知(切面要完成的功能)
Aspect(切面): 是切入点和通知(引介)的结合
Introduction(引介):引介是一种特殊的通知在不修改类代码的前提下, Introduction可以在运行期为类动态地添加一些方法或Field.
Target(目标对象):代理的目标对象(要增强的类)
Weaving(织入):是把增强应用到目标的过程.
把advice 应用到 target的过程
Proxy(代理):一个类被AOP织入增强后,就产生一个结果代理类
1.xml配置方式实现
a.Book.class
public class Book {
public void showBook() {
System.out.println("this is a book");
}
}
b.MyBook.class加在book的方法类
public class MyBook {
public void before() {
System.out.println("this is before");
}
}
c.在applicationContext.xml加入aop配置
-->
d.测试
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Book book = (Book) context.getBean("book");
book.showBook();
}
2.注解方式实现
a.在applicationContext.xml加入aop注解
b.myBook.class
@Aspect
public class MyBook2 {
@Pointcut("execution(* aop.Book2.showBook(..))")
public void showBook() {}
@Before("showBook")
public void before() {
System.out.println("this is before2");
}
}