spring-入门

摘要:
/豆>标记为控制器组件类@ControllerpublicclassUserController{}@服务:标记为业务逻辑组件类@ServicepublicclassUserService{}@组件:标记为基本spring bean组件类@ComponentpublicclassHouse{}@Repository:

1.spring是什么?

  spring是一个轻量型的框架,主要体现在管理每一个Bean组件的生命周期,不同Bean组件之间依赖关系上面。

  它主要是通过顶层容器BeanFactory来管理每一个Bean组件的生命周期,通过子类ApplicationContext实现工厂模式下每一个Bean组件的创建。

2.两大核心:

  IOC/DI:控制反转/依赖注入,service层注入dao层,action层(controller)注入service层

  AOP:面向切面编程

3.控制反转的作用:

  将对象的创建通过配置文件来声明,通过spring提供的容器进行创建,创建的bean对象为单例对象,同时通过配置文件或者注解来描述不同Bean组件之间的依赖关系。

4.依赖注入的实现方式:

1) 构造器注入:

 <bean id="constructor" class="com.wsw.entity.User">
        <constructor-arg name="" value="" ref=""/>
        <constructor-arg name="" value="" ref=""/>
    </bean>

2)传值注入/setter注入:

  <bean id="constructor" class="com.wsw.entity.User">
        <property name="" value=""/>
        <property name="" value=""/>
        <property name="" value=""/>
    </bean>

3)接口注入

5.AOP的实现原理

 1)jdk动态代理:仅支持接口的注入

 2)cglib植入:支持普通类的注入

6.spring的事务:

1)编程式事务:通过编程的方式实现事务,具有极大的灵活性,但是难以维护。通过使用TransactionTemplate或者直接使用底层的PlatformTransactionManager进行事务相关特性的实现。

2)声明式事务:可以将业务代码和事务管理分离,使用注解或者配置文件来管理事务。如加注解@Transactional或者通过xml进行配置。

7.spring的常用注解:

@Controller:标注为一个控制器组件类

@Controller
public class UserController {}

@Service:标注为一个业务逻辑组件类

@Service
public class UserService {}

@Component:标注为一个基本的spring bean组件类

@Component
public class House {}

@Repository:标注为一个dao层组件类

 1 @Repository
 2 public interface UserDao {
 3 
 4     /**
 5      * 查看所有用户
 6      * @return
 7      */
 8     List<User> selectAll();
 9 
10     /**
11      * 插入一条用户记录
12      * @param user
13      */
14     void insertOne(User user);
15 
16     /**
17      * 分页查询
18      * @param pageNum:偏移量,代表从第pageNum+1的位置开始取记录
19      * @param pageCount:取记录的总数
20      * @return
21      */
22     List<User> selectByPageNo(@Param("pageNum") int pageNum, @Param("pageCount") int pageCount);
23 
24     /**
25      * 查询所有记录数
26      * @return
27      */
28     int selectTotalCount();
29 
30 }

@Autowired:根据类型自动注入,由spring提供

@Controller
public class HouseController {
    @Autowired
    private HouseService houseService;
    @Autowired
    private UserService userService;
}

@Resource:默认根据名称自动注入,也可以根据类型自动注入。由J2EE提供,使用的话需要在jdk1.6及以上版本

public class UnitTest extends BaseTest {
    @Resource
    private UserDao userDao;
}

@Transactional:声明事务特性

 1 @Transactional
 2 public class AopTest {
 3 
 4     public void before(JoinPoint joinPoint) throws Throwable {
 5         System.out.println("前置"+joinPoint.getTarget().getClass().getName());
 6     }
 7 
 8     public void after(JoinPoint joinPoint) throws Throwable {
 9         System.out.println("后置"+joinPoint.getTarget().getClass().getName());
10     }
11 
12 }

8.spring的优缺点:

优点:降低了对象之间的耦合度,使代码更加清晰,并且能够提供一些常见的模板。

缺点:内容广泛比较难理解,需要不断地深入每一块的学习才能真正掌握(个人理解)

9.spring框架中能够体现哪些设计模式?

1)工厂模式:主要体现在每一个bean组件的创建过程

2)代理模式:主要体现在面向切面编程AOP的实现

3)单例模式:主要体现在每一个bean组件创建后的状态

10.spring框架中的配置内容主要有哪些?

1)开启注解功能,配置扫描包

    <context:annotation-config/>
    <context:component-scan base-package="com.wsw.*"/>

注意:组件扫描component-scan里面其实已经包含了注解自动配置annotation-config,所以只要配置组件扫描即可

2)数据源的配置

  <!-- 配置数据源 -->
    <context:property-placeholder location="classpath:db.properties"/>
    <bean id="dataSource" class="${dataSource}" destroy-method="close">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

3)会话工厂配置(融合了Mybatis相关配置)

  <!-- 配置sqlSessionFactory,SqlSessionFactoryBean是用来产生sqlSessionFactory的 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 加载mybatis的全局配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!-- 加载数据源,使用上面配置好的数据源 -->
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.wsw.entity"/>
        <property name="mapperLocations" value="classpath*:mapper/*-mapper.xml"/>
    </bean>

4)事务管理配置

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

5)aop配置

1.基于xml文件配置

<aop:config proxy-target-class="true">
        <aop:pointcut id="pc" expression="execution(* com.wsw.service..*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pc"/>
        <aop:aspect>
            <aop:before method="before" pointcut-ref="pc"/>
            <aop:after method="after" pointcut-ref="pc"/>
            <aop:around method="around" pointcut-ref="pc"/>
        </aop:aspect>
    </aop:config>
2.基于全注解,需要在配置文件中添加切面类自动代理
spring-入门第1张

(1)切面类
 1 @Component
 2 @Aspect
 3 public class AopTest {
 4 
 5     @Before(value = "execution(* com.sunsharing.service.UserService.*(..))")
 6     public void before(JoinPoint joinPoint) throws Throwable {
 7         System.out.println("aop前置通知-->"+joinPoint.getThis().getClass().getName());
 8     }
 9 
10     @After(value = "execution(* com.sunsharing.service.UserService.*(..))")
11     public void after(JoinPoint joinPoint) throws Throwable {
12         System.out.println("aop后置通知-->"+joinPoint.getThis().getClass().getName());
13     }
14 
15   /*  @AfterReturning
16     public void afterReturn(JoinPoint joinPoint) throws Throwable{
17         System.out.println("aop环绕通知-->"+joinPoint.getThis().getClass().getName());
18     }
19 
20     @AfterThrowing
21     public void afterThrow(JoinPoint joinPoint) throws Throwable{
22         System.out.println("aop异常通知-->"+joinPoint.getThis().getClass().getName());
23     }*/
24 
25     public void print(){
26         System.out.println("init");
27     }
28 
29 }

(2)测试类:

1 @RunWith(SpringJUnit4ClassRunner.class)
2 @ContextConfiguration("classpath:applicationContext.xml")
3 public class BaseTest {
4 }
 1 public class UnitTest extends BaseTest {
 2     @Autowired
 3     private UserService userService;
 4 
 5     @Test
 6     public void showAllTwo() {
 7         Page<User> page = userService.selectByPage(3, 2);
 8         List<User> list = page.getLists();
 9         for (User u : list) {
10             System.out.println(u);
11         }
12         System.out.println("总页数为:" + page.getTotalPage());
13         System.out.println("总记录数:" + page.getTotalCount());
14     }
15 
16 }

效果截图:

spring-入门第2张

spring-入门第3张

11.Spring的七大核心模块:

  • Core(容器管理):spring 的核心容器提供bean组件的创建,将bean组件之间的依赖关系通过配置文件或者注解的方式进行管理,将应用的配置与实际的代码分开,实现解耦性。
  • Aop(面向切面编程):spring aop为spring中的对象提供了事务管理的功能,将面向切面编程的理论成功实践在spring框架中,允许通过配置或者注解的方式实现切面化编程。
  • Orm(对象-关系映射):spring orm在spring框架的基础上添加了若干个orm框架,使得spring框架可以与mybatis,hibernate,ibatis等框架工具连用。
  • Dao(jdbc连接与dao层模块):将数据库连接的创建,销毁,异常捕获等等进行封装,在dao层与jdbc数据库操作之间建立某种联系,简化数据库与实体类的相关操作。
  • Webmvc(mvc模块):将mvc三层分离模型融入spring框架中,使得spring框架能够实现前后端的不同方式组合。如spring+strut2+mybatis,spring+spring mvc+mybatis等等。
  • Context(上下文管理):相当于一个配置文件,由它管理上下文路径,内容,配置信息等等,使得spring框架的搭建更加高效,快速。
  • Web(web模块):在上下文管理的基础上添加web模块,为基于web应用程序提供了上下文模块管理。


 

免责声明:文章转载自《spring-入门》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇构建 Owin 中间件 来获取客户端IP地址元数据MetaData下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

浅谈java中线程和操作系统线程

  在聊线程之前,我们先了解一下操作系统线程的发展历程,在最初的时候,操作系统没有进程线程一说,执行程序都是串行方式执行,就像一个队列一样,先执行完排在前面的,再去执行后面的程序,这样的话很多程序的响应就很慢,而且有些程序是io型操作居多,很多时间都在等待中浪费了,这时候进程应运而生,现在面试的都知道进程是资源管理的最小单位,线程是cpu调度的最小单位(其...

Vue2.0进阶组件 短信倒计时组件

原本我想隔个几天再发文章,刚好今天项目上线,环境有问题,导致只有干等,刚好要为公司打造一套属于公司自己的一系列功能组件,这个使命就交给我了,大家也一直叫我来点干货,说实话我只是一个湿货,肚子里干一点就给你们出点货,那从今天开始不看岛国片系列教程视频,不但自撸,还教你撸............你懂的!!最强vue组件 写之前我只想说如果看到错别字,就别给我点...

HTML5新特性之文字转语音

/** * 文字转语音,利用H5的新特性SpeechSynthesisUtterance,speechSynthesis实现 * eg. * const speaker = new Speaker({ text: '这是一条神奇的天路啊' }); * speaker.start(); // 开时播放 * setTimeout((...

Springboot 整合Jersey

  在查看EurekaServer 服务端代码时偶然看到Jersey这个东西,简单记录下。 1. 简介   Jersey是一个RESTFUL请求服务JAVA框架,与常规的JAVA编程使用的struts框架类似,它主要用于处理业务逻辑层。   1.X的版本是sun公司提供的独立的jar包,在2.X版本中已经将jersey融合到JavaSE中,在javax.w...

dump redo日志文件的信息

通常会用到以下两个命令:1.'alter session'命令用来dump redo日志的文件头2.'alter system dump logfile'命令用来dump redo文件的内容 以上命令也可以对归档日志进行dump。输出结果存放在session的trace文件中。 可以根据以下方式对redo日志进行dump:(1) To dump recor...

Freeswitch配置之sofia

   SIP模块 - mod_sofia SIP 模块是 FreeSWITCH的主要模块。 在 FreeSWITCH中,实现一些互联协议接口的模块称为 Endpoint。FreeSWITH支持很多的 Endpoint,如 SIP、H232等。那么实现 SIP 的模块为什么不支持叫 mod_sip呢?这是由于 FreeSWITCH的 Endpoint 是一个...