Spring偷懒笔记(配置文件,拷贝可用)

Jammm
2020-06-23 / 0 评论 / 441 阅读 / 正在检测是否收录...

Powered By JamPang

QQ:847885907

https://jampang.cn/

Spring笔记

1、Maven导入Spring包

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.6.RELEASE</version>
</dependency>

2、Spring配置头(beans.xml/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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">


</beans>

2.1、配置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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="mysqlImpl" class="com.jam.dao.UserDaoMysqlImpl"/>
    <bean id="oracleImpl" class="com.jam.dao.UserDaoOracleImpl"/>

    <bean id="UserServiceImpl" class="com.jam.service.UserServiceImpl">
        <!--
        ref:引用Spring容器汇总创建好的对象
        value:具体的值,基本数据类型
        注意: 这里的name并不是属性 , 而是set方法后面的那部分 , 首字母小写
        -->
        <property name="userDao" ref="oracleImpl"/>
    </bean>

</beans>

2、依赖注入

  • 依赖注入(Dependency Injection,DI)。
  • 依赖 : 指Bean对象的创建依赖于容器,Bean对象的依赖资源。
  • 注入 : 指Bean对象所依赖的资源,由容器来设置和装配。

2.1、构造器注入

  1. 使用无参构造创建对象,默认!
  2. 假设我们要使用有参构造创建对象。

    1. 下标赋值

      <!--第一种,下标赋值-->
      <bean id="user" class="com.jam.pojo.User">
          <constructor-arg index="0" value="jam"/>
      </bean>
    2. 类型

      <!--第二种,通过类型创建,不建议使用!-->
      <bean id="user" class="com.jam.pojo.User">
          <constructor-arg type="java.lang.String" value="jam2"/>
      </bean>
    3. 参数名

      <!--第三种,直接通过参数名来设置-->
      <bean id="user" class="com.jam.pojo.User">
          <constructor-arg name="name" value="jam3"/>
      </bean>

总结:在配置文件加载的时候,容器中的对象就已经初始化了!

2.2、Set方式注入【重点】

  • 依赖注入:Set注入!

    • 依赖:bean对象的创建依赖于容器!
    • 注入:bean对象中的所有属性,由容器来注入!
  1. 【环境搭建】

    1. 复杂类型 Address.java

      public class Address {
          private String address;
      
          public String getAddress() {
              return address;
          }
      
          public void setAddress(String address) {
              this.address = address;
          }
      }
  1. 真实测试对象 Student.java

    public class Student {
    
        private String name;
        private Address address;
        private String[] books;
        private List<String> hobbys;
        private Map<String,String> card;
        private Set<String> games;
        private Properties info;
        private String wife;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Address getAddress() {
            return address;
        }
    
        public void setAddress(Address address) {
            this.address = address;
        }
    
        public String[] getBooks() {
            return books;
        }
    
        public void setBooks(String[] books) {
            this.books = books;
        }
    
        public List<String> getHobbys() {
            return hobbys;
        }
    
        public void setHobbys(List<String> hobbys) {
            this.hobbys = hobbys;
        }
    
        public Map<String, String> getCard() {
            return card;
        }
    
        public void setCard(Map<String, String> card) {
            this.card = card;
        }
    
        public Set<String> getGames() {
            return games;
        }
    
        public void setGames(Set<String> games) {
            this.games = games;
        }
    
        public Properties getInfo() {
            return info;
        }
    
        public void setInfo(Properties info) {
            this.info = info;
        }
    
        public String getWife() {
            return wife;
        }
    
        public void setWife(String wife) {
            this.wife = wife;
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", address=" + address +
                    ", books=" + Arrays.toString(books) +
                    ", hobbys=" + hobbys +
                    ", card=" + card +
                    ", games=" + games +
                    ", info=" + info +
                    ", wife='" + wife + '\'' +
                    '}';
        }
    }
  1. beans.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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <bean id="student" class="com.jam.pojo.Student">
            <!--第一种,普通值注入,value-->
            <property name="name" value="Jam"/>
        </bean>
    
    </beans>
  1. 测试类

    public class MyTest {
    
        public static void main(String[] args) {
    
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            Student student = (Student) context.getBean("student");
            System.out.println(student.getName());
        }
    
    }

完善注入信息

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="address" class="com.jam.pojo.Address">
        <property name="address" value="江西"/>
    </bean>


    <bean id="student" class="com.jam.pojo.Student">

        <!--第一种,普通值注入,value-->
        <property name="name" value="Jam"/>

        <!--第二种,Bean注入,ref-->
        <property name="address" ref="address"/>

        <!--数组注入-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>西游记</value>
                <value>水浒传</value>
                <value>三国演义</value>
            </array>
        </property>

        <!-- List -->
        <property name="hobbys">
            <list>
                <value>听歌</value>
                <value>敲代码</value>
                <value>看电影</value>
            </list>
        </property>

        <!-- Map -->
        <property name="card">
            <map>
                <entry key="身份证" value="111111222222223333"/>
                <entry key="银行卡" value="6222021505001111111"/>
            </map>
        </property>

        <!-- Set -->
        <property name="games">
            <set>
                <value>LOL-英雄联盟</value>
                <value>COC-部落冲突</value>
                <value>BOB-球球大作战</value>
            </set>
        </property>

        <!-- null -->
        <property name="wife">
            <null/>
        </property>

        <!-- Properties -->
        <property name="info">
            <props>
                <prop key="学号">20200527</prop>
                <prop key="性别">男</prop>
                <prop key="姓名">旧梦</prop>
            </props>
        </property>

    </bean>

</beans>

2.3、拓展方式注入[p命名/c命名注入]

我们可以使用p命名空间和c命名空间进行注入

p命名包

xmlns:p="http://www.springframework.org/schema/p"

c命名包

xmlns:c="http://www.springframework.org/schema/c"

beans.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:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- p命名空间注入,可以直接注入属性的值:property -->
    <bean id="user" class="com.jam.pojo.User" p:name="Jam" p:age="18"/>

    <!-- c命名空间注入,通过构造器注入:construct-args -->
    <bean id="user2" class="com.jam.pojo.User" c:name="Tim" c:age="18"/>

</beans>

测试

@Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
        User user = context.getBean("user",User.class);
        System.out.println(user);
    }

    @Test
    public void test3(){
        ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
        User user = context.getBean("user2",User.class);
        System.out.println(user);
    }

注意:p命名和c命名空间不能直接使用,需要导入xml约束!

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"

2.4、Set详细注入方式

具体类请参考2、依赖注入

2.4.1、普通注入,value

<!--第一种,普通值注入,value-->
<property name="name" value="Jam"/>

2.4.2、Bean注入,ref

 <!--第二种,Bean注入,ref-->
<property name="address" ref="address"/>

2.4.3、数组注入

<!--数组注入-->
<property name="books">
    <array>
        <value>红楼梦</value>
        <value>西游记</value>
        <value>水浒传</value>
        <value>三国演义</value>
    </array>
</property>

2.4.4、List注入

 <!-- List -->
<property name="hobbys">
    <list>
        <value>听歌</value>
        <value>敲代码</value>
        <value>看电影</value>
    </list>
</property>

2.4.5、Map注入

<property name="card">
    <map>
        <entry key="身份证" value="111111222222223333"/>
        <entry key="银行卡" value="6222021505001111111"/>
    </map>
</property>

2.4.6、Set注入

<!-- Set -->
<property name="games">
    <set>
        <value>LOL-英雄联盟</value>
        <value>COC-部落冲突</value>
        <value>BOB-球球大作战</value>
    </set>
</property>

2.4.7、null注入

<!-- null -->
<property name="wife">
    <null/>
</property>

2.4.8、Properties注入

<!-- Properties -->
<property name="info">
    <props>
        <prop key="学号">20200527</prop>
        <prop key="性别">男</prop>
        <prop key="姓名">旧梦</prop>
    </props>
</property>

2.4.9、输出信息

/***
     * Student{name='Jam', address=Address{address='江西'},
     * books=[红楼梦, 西游记, 水浒传, 三国演义],
     * hobbys=[听歌, 敲代码, 看电影],
     * card={身份证=111111222222223333, 银行卡=6222021505001111111},
     * games=[LOL-英雄联盟, COC-部落冲突, BOB-球球大作战], i
     * nfo={学号=20200527, 性别=男, 姓名=旧梦},
     * wife='null'}
     */

3、自动装配

3.1、ByName

bean.xml

<!--
     byName:会自动在容器上下文中查找和自己对象set方法后面的值对应的beanid
-->
<bean id="cat" class="com.jam.pojo.Cat"/>
<bean id="dog" class="com.jam.pojo.Dog"/>

<bean id="people" class="com.jam.pojo.People" autowire="byName">
    <property name="name" value="Jam"/>
</bean>

3.2、ByType自动装配

<!--
     byType:会自动在容器上下文中查找和自己对象属性类型相同的bean
-->
<bean class="com.jam.pojo.Cat"/>
<bean class="com.jam.pojo.Dog"/>

<bean id="people" class="com.jam.pojo.People" autowire="byType">
    <property name="name" value="Jam"/>
</bean>

3.3、byName/byType小结

  • byName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
  • byType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致

3.4、使用注解实现自动装配

jdk1.5支持的注解,spring从2.5支持注解。

The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML. The short answer is “it depends.”

要使用注解须知:

  1. 导入约束 context约束
  2. 配置注解的支持

    <?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:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:annotation-config/>
    
    </beans>

@Autowired

直接在属性上使用即可,也可以在Set方式上使用!

使用Autowired我们可以不用编写Set方法了,前提是你的自动装配的属性在IOC(Spring)容器存在,且符合名字byname!

科普:

@Nullable  字段标记了这个注解,说明这个字段可以为null
public @interface AutoWired{
    boolean required() default true;
}

测试代码

//如果显示定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
@Autowired(required = false)
private Cat cat;
@Autowired
private Dog dog;
private String name;

如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qulifier(value="XXX")去配置@Autowired的使用,指定一个唯一的bean对象注入!

@Autowired
@Qulifier(value="cat111")
private Cat cat;
@Autowired
@Qulifier(value="222")
private Dog dog;
private String name;

@Resource注解

public class People(){
    
    @Resource(name="cat2")
    private Cat cat;
    
    @Resource
    private Dog dog;
}

7.6、注解小结

@Resource和@Autowired的区别:

  • 都是用来自动装配的,都可以放在属性字段上。
  • @Autowired通过byType的方式现实
  • @Resource默认通过byName的方式实现,如果找不到名字,则通过byType实现。如果两个都找不到的情况下就报错。【常用】
  • 执行顺序不同:@Autowired通过byType的方式现实,@Resource默认通过byName的方式实现

4、使用注解开发

在Spring4之后要使用注解开发,必须要使用aop包

使用注解需要导入context约束,增加注解的支持。

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

</beans>

4.1、bean

 <!-- 指定要扫描的包,这个包下的注解就会生效 -->
<context:component-scan base-package="com.jam"/>
<context:annotation-config/>

4.2、属性如何注入

//等价于 <bean id="user" class="com.jam.pojo.User">
//@Component组件
@Component
public class User {

    //public String name = "Jam";

    // @Value("Jam")
    // 相当于 <property name="name" value="Jam"/>
    @Value("Jam")
    public String name;
}

4.3、衍生的注解

@Component有几个衍生注解,我们在web开发中,会按照mvc三层架构分层。

  • dao【@Repository】
  • service【@Service】
  • controller【@Controller】

    四个注解都是代表将某个类注册到Spring中,装备Bean。

  1. 自动装配

    @Autowired:自动装配通过类型、名字
        如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value="xxx")
    @Nullable:字段标记了这个注解,说明这个字段可以为null
    @Resource:自动装配通过类型、名字
  1. 作用域

    package com.jam.pojo;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Component;
    
    //等价于 <bean id="user" class="com.jam.pojo.User">
    //@Component组件
    @Component
    @Scope("prototype")
    public class User {
    
        //public String name = "Jam";
    
        // @Value("Jam")
        // 相当于 <property name="name" value="Jam"/>
        @Value("Jam")
        public String name;
    }
    

4.4、小结

xml与注解:

  • xml更加万能,适用于任何场合,维护简单方便。
  • 注解 不是自己的类使用不了,维护相对复杂!

xml与注解最佳实践:

  • xml用来管理bean
  • 注解只负责完成属性的注入
  • 我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持

    <!-- 指定要扫描的包,这个包下的注解就会生效 -->
    <context:component-scan base-package="com.jam"/>
    <context:annotation-config/>

5、整合Mybatis

5.1、mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
     <typeAliases>
         <package name="com.jam.pojo"/>
     </typeAliases>

    <!--设置-->
<!--    <settings>-->
<!--        <setting name="" value=""/>-->
<!--    </settings>-->

</configuration>

5.2、spring-dao.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">



    <!-- DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid
        我们这里使用Spring提供的JDBC:org.springframework.jdbc.datasource
    -->

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="1234"/>

    </bean>


    <!-- sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--绑定Mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/jam/mapper/*.xml"/>
    </bean>

    <!--SqlSessionTemplate:就是我们使用的SqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

</beans>

5.3、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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">


    <import resource="spring-dao.xml"/>

    <!---->
    <bean id="userMapper" class="com.jam.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

</beans>

5.4、SqlSessionTemplate用法

package com.jam.mapper;

import com.jam.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserMapperImpl implements UserMapper{

    //我们的所有操作都使用sqlSession来执行,现在都使用SqlSessionTemplate
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    public List<User> selectUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

5.5、测试

@Test
public void test() throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
    for (User user : userMapper.selectUser()) {
        System.out.println(user);
    }
}

6、Spring事务

  • 声明式事务:AOP
  • 编程时事务:需要在代码中,进行事务的管理

为什么要事务?

  • 如果不配置书屋,可能存在数据提交不一致的情况。
  • 如果我们不在Spring中去配置声明事务,我们就需要在代码中手动配置事务。
  • 配置在项目的开发中十分重要,设计到数据的一致性和完整性问题。
<!--配置事务声明-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--结合AOP进行事务-->
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <!--配置事务的传播特性:new  propagation-->
        <tx:attributes>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <!--配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.jam.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
本文共 1539 个字数,平均阅读时长 ≈ 4分钟
0

打赏

海报

正在生成.....

评论 (0)

取消