Spring详解

目录

Spring简介

Spring入门开发步骤

Bean标签

Bean注解

JDK:基于接口的动态代理

cglib:基于父类的动态代理

AOP基于XML的AOP入门开发

基于注解的AOP入门开发


Spring简介

Spring是分层的 Java SE/EE应用 full-stack(全栈式) 轻量级开源框架,以 IoC(Inverse of Control:控制反转)和 AOP(Aspect Oriented Programming:面向切面编程)为核心。
提供了展现层 SpringMVC 和持久层 Spring JDBCTemplate 以及业务层事务管理等众多的企业级应用技术,还能整合开源世界众多著名的第三方框架和类库,逐渐成为使用最多的Java EE 企业应用开源框架。

IoC:对象的创建、初始化、销毁由IoC容器管理。
DI:依赖注入(Dependency Injection):IoC容器在运行期间,动态地将依赖关系注入到对象之中。由IoC容器帮对象找相应的依赖对象并注入,而不是由对象主动去找。
AOP:不修改原有方法代码,增强原有方法的功能。

 

Spring入门开发步骤

1、在pom.xml中配置Spring的基本包坐标
2、编写Dao接口和DaoImpl实现类
3、创建Spring核心配置文件applicationContext.xml,并配置DaoImpl实现类
4、在测试类中,通过getBean()获得Bean实例

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
    </dependencies>

public interface MyDao {
    public void call();
}

public class MyDaoImpl implements MyDao {
    @Override
    public void call() {
        System.out.println("MyDaoImpl call......");
    }
}

<bean id="myDao" class="com.cn.dao.impl.MyDaoImpl"></bean>

public class MyDaoDemo {
    public static void main(String[] args) {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        //MyDao myDao = app.getBean(MyDao.class);
        MyDao myDao = (MyDao) app.getBean("myDao");
        myDao.call();
    }
}

⑤ 运行结果:MyDaoImpl call......

Bean标签

Bean标签属性
<bean id="" class="" scope=""  init-method="" destroy-method="">
scope : singleton、prototype、request、session、application
当scope="singleton",加载applicationContext.xml时,实例化配置的bean对象
当scope="prototype",调用getBean()时,实例化配置的Bean对象

Bean生命周期配置
init-method:指定类中的初始化方法 
destroy-method:指定类中的销毁方法

Bean实例化方式
无参构造方法(推荐)
工厂静态方法
工厂实例方法

Bean的依赖注入方式
有参构造方法
set方法,包括p命名空间

Bean的依赖注入的数据类型
普通数据类型 String Integer
引用数据类型 对象
集合数据类型 Array List Map Properties

Bean注解

Bean注解配置:

  1. 在applicationContext.xml中配置context命名空间及约束。
  2. 开启注解扫描
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

<!--开启注解扫描-->
<context:component-scan base-package="com.cn"></context:component-scan>
    
注解说明
@Component在类上用于实例化Bean 
@Controller在web层类上用于实例化Bean
@Service在service层类上用于实例化Bean
@Repository在dao层类上用于实例化Bean
@Autowired在成员变量、方法及构造函数上,根据类型自动装配
@Qualifier结合@Autowired,根据名称依赖注入
@Resource相当于@Autowired+@Qualifier,根据名称依赖注入
@Value注入普通数据
@Scopesingleton / prototype
@PostConstruct在方法上,标注方法是初始化方法
@PreDestroy

在方法上,标注方法是销毁方法

@Configuration标注该类是Spring配置类,创建容器时加载该类的注解
@ComponentScan标注注解扫描的包
@Bean标注方法,该方法的返回值存储到Spring容器中
@PropertySource()加载.properties的配置
@Import()导入其它配置类

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ms
jdbc.username=root
jdbc.password=root
@Configuration
@ComponentScan(value = "com.cn")
@Import({DataSourceConfiguration.class}) //数组
public class SpringConfiguration {

}
@PropertySource(value = "classpath:jdbc.properties")
public class DataSourceConfiguration {

    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean(value = "dataSource")
    public DataSource getDataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);

        return dataSource;
    }
}
public class MyController {

    public static void main(String[] args) {
        //ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        MyService ms = (MyService) app.getBean("myService");
        ms.call();

    }
}

JDK:基于接口的动态代理

public interface TargetInterface {
    public void hello();
}

public class Target implements TargetInterface{

    public void hello() {
        System.out.println("hello jdk proxy......");
    }
}

public class Advice {

    public void before(){
        System.out.println("前置增强......");
    }
    public void afterReturning(){
        System.out.println("后置增强......");
    }

}

public class ProxyTest {
    public static void main(String[] args) {
        //目标对象
        Target target = new Target();
        //增强对象
        Advice advice = new Advice();

        // 返回动态生成的代理对象
        TargetInterface proxy = (TargetInterface) Proxy.newProxyInstance(
                target.getClass().getClassLoader(), //目标对象类加载器
                target.getClass().getInterfaces(), //目标对象的相同接口字节码对象数组
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        advice.before(); // 前置增强
                        Object invoke = method.invoke(target, args);//执行目标方法
                        advice.afterReturning(); //后置增强
                        return invoke;
                    }
                }
        );

        proxy.hello();
    }
}

前置增强......
hello jdk proxy......
后置增强......

cglib:基于父类的动态代理

public class Target {
    public void hello() {
        System.out.println("hello cglib proxy......");
    }
}

public class Advice {
    public void before(){
        System.out.println("cglib前置增强......");
    }
    public void afterReturning(){
        System.out.println("cglib后置增强......");
    }
}


public class ProxyTest {
    public static void main(String[] args) {
        //目标对象
        Target target = new Target();
        //增强对象
        Advice advice = new Advice();
        // 返回动态生成的代理对象
        // 1. 创建增强器
        Enhancer enhancer = new Enhancer();
        // 2. 设置父类(目标)
        enhancer.setSuperclass(Target.class);
        // 3. 设置回调
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                advice.before();//执行前置增强方法
                Object invoke = method.invoke(target, args);//执行目标方法
                advice.afterReturning();//执行后置增强方法
                return invoke;
            }
        });
        // 4. 创建代理对象
        Target proxy = (Target) enhancer.create();
        proxy.hello();
    }
}

cglib前置增强......
hello cglib proxy......
cglib后置增强......

AOP思维导图

基于XML的AOP入门开发

  1. 在pom.xm中配置aspectj、spring-test、junit坐标
  2. 创建目标接口类、目标类、切面类
  3. 在applicationContext.xml中配置目标类、切面类,及配置织入关系
  4. 测试

       <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.0.RELEASE</version>
            <scope>test</scope>
        </dependency>

public interface TargetInterface {
    public void hello();
}

public class Target implements TargetInterface {
    public void hello() {
        System.out.println("hello aop......");
    }
}

public class MyAspect {
    public void before(){
        System.out.println("before advice......");
    }
}

    <!--目标对象-->
    <bean id="target" class="com.cn.proxy.aop.Target"></bean>
    <!--切面对象-->
    <bean id="myAspect" class="com.cn.proxy.aop.MyAspect"></bean>
    <!--配置织入,告诉Spring框架 哪些方法(切点)需要哪些增强-->
    <aop:config>
        <aop:aspect ref="myAspect">
            <aop:before method="before" pointcut="execution(public void com.cn.proxy.aop.Target.hello())"/>
        </aop:aspect>
    </aop:config>

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AopTest {

    @Resource(name = "target")
    private TargetInterface targetInterface;
    @Test
    public void test(){
        targetInterface.hello();
    }
}

before advice......
hello aop......
        <aop:aspect ref="myAspect">
            <!--切点表达式抽取-->
            <aop:pointcut id="myPointcut" expression="execution(* com.cn.*.*(..))"/>
            <aop:before method="before" pointcut-ref="myPointcut"/>
        </aop:aspect>

基于注解的AOP入门开发

public interface TargetInterface {
    public void hello();
}

@Component("target")
public class Target implements TargetInterface {
    public void hello() {
        System.out.println("hello aop annotation......");
    }
}


@Component("myAspect")
@Aspect
public class MyAspect {
    @Before("execution(public void com.cn.proxy.aopanno.Target.hello())")
    public void before(){
        System.out.println("before advice annotation......");
    }
}
    <!--开启注解扫描-->
    <context:component-scan base-package="com.cn"></context:component-scan>
    <!--AOP自动代理-->
    <aop:aspectj-autoproxy/>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-anno.xml")
public class AopAnnoTest {

    @Resource(name = "target")
    private TargetInterface targetInterface;
    @Test
    public void test(){
        targetInterface.hello();
    }
}

before advice annotation......
hello aop annotation......

AOP使用场景:

Authentication 权限
Caching 缓存
Context passing 内容传递
Error handling 错误处理
Lazy loading 懒加载
Debugging  调试
logging, tracing, profiling and monitoring 记录跟踪 优化 校准
Performance optimization 性能优化
Persistence  持久化
Resource pooling 资源池
Synchronization 同步
Transactions 事务

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值