spring学习小结

本文详细介绍了Spring框架中的IoC(控制反转)和DI(依赖注入)概念,包括bean的创建、配置以及不同类型的注入方式。此外,还探讨了Spring的AOP(面向切面编程),包括静态代理、注解实现和原生API的使用。最后,提到了Spring与MyBatis的整合以及事务管理。
摘要由CSDN通过智能技术生成

Spring

bean:使用Spring来创建对象,在Spring中这些都称为bean类型 变 量名 = new 类型()
bean = 对象 Hello hello = new hello()
id = 变量名
class = new 的对象
property 相当于给对象中的属性设置一个值

IOC容器

spring创建对象的方法
1.下标赋值
2.通过类型创建不建议使用
3.直接通过参数名设置

<?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
        http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--第一种:下标赋值-->
	<bean id="user" class="com.jie.pojo.User">
	 	<constructor-arg index="0" value=""/>
	</bean>
<!--第二种:通过类型创建不建议使用-->
	<bean id="user" class="com.jie.pojo.User">
		<constructor-arg type="java.lang.String" value="jie"/>
	</bean>
<!--第三种:直接通过参数名设置-->
<bean id="user" class="com.jie.pojo.User">
    <constructor-arg name="name" value=""/>
</bean>
<!--
    id: bean的唯一标识符,也就是相当于我们的对象名
    class:bean 对象所对应的全限定名:包名 + 类名
    name:也是取别名,而且name可以同时取多个别名
-->
<bean id="userT" class="com.jie.pojo.UserT" name="userT2 u2,u3">
    <property name="name" value=""/>
</bean>
<!--取别名 取了别名本来的名字还能用-->
<alias name="user" alias="user2"/>

<!--导入- -》 导入的文件中的 bean 在这里也能拿到-->
<import resource="beans.xml"/>
<import resource="beans2.xml"/>

</beans>

DI

不同类型的注入方式
实体类 Student

 private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String,String> card;
    private Set<String> games;
    private String wife;
    private Properties info;
    

在配置文件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
        http://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="address" class="com.jie.pojo.Address">
        <property name="address" value="武汉"/>
    </bean>
    <bean id="student" class="com.jie.pojo.Student">

        <!--第一种:普通注入  value-->
        <property name="name" value="小红"/>

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

        <!--第三种:数组注入-->
        <property name="books">
          <array>
              <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="212132545665"/>
                <entry key="银行卡" value="54654565654456"/>
            </map>
        </property>

        <!--set注入-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>CSGO</value>
                <value>PUBG</value>
            </set>
        </property>

        <!--null值注入-->
        <property name="wife">
            <null>/</null>
        </property>

        <!--properties-->
        <property name="info">
            <props>
                <prop key="driver">121302654</prop>
                <prop key="sex"></prop>
                <prop key="name">小明</prop>
                <prop key="password">12363</prop>
            </props>
        </property>
    </bean>



</beans>


自动装配

在实体类中使用注解:

public class Person {

    // 如果显示的定义了Autowired的required属性为false,说明这个属性可以为null,否则不允许为空
    @Autowired(required = false)
    @Qualifier(value = "cat12")
    private Cat cat;

    @Resource
    private Dog dog;



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

    <!--开启注解支持-->
    <context:annotation-config/>

    <bean id="cat12" class="com.jie.pojo.Cat"/>
    <bean id="dog2" class="com.jie.pojo.Dog"/>
    <!--
    byName自动装配
        byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid
   byType自动装配
        byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean
    -->
    <bean id="person" class="com.jie.pojo.Person"/>

</beans>

使用注解

// 等价于 <bean id="user" class="com.jie.pojo.User"/>
// @Component 组件
@Component
@Scope("prototype")
public class User {
    // 相当于  <property name="name" value="jie"/>
    @Value("jie")
    public String name;
}

dao层使用:@Repository
service使用:@service
controller层使用:@Controller

配置文件中只需要开启注解,并且指定要扫描的包。

完全使用配置类实现

实体类User:

// 这里这个注解的意思,就是说这个类被spring接管了
@Component
public class User {
    @Value("jie")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

config:

// 这个也会被spring容器托管,注册到容器中,因为他本来就是一个@Component
//@Configuration代表这是一个配置类,就和我们之前看的beans.xml一样
@Configuration
@ComponentScan("com.jie.pojo")
@Import(JieConfig2.class )
public class JieConfig {

    // 注册一个bean,就相当于之前写的bean标签
    // 这个方法的名字,就相当于bean标签中的id
    // 这个方法的返回值,就相当于bean标签中的class属性
    @Bean
    public User getUser(){

        return new User();//就是注入到bean的对象
    }
}

config2:

@Configuration
public class JieConfig2 {
}

测试类

public class MyTest {
    public static void main(String[] args) {
        // 如果完全使用了配置类方式去做,我们就只能通过 AnnotationConfig 上下文来获取容器,通过配置类的class对象加载
        ApplicationContext context = new AnnotationConfigApplicationContext(JieConfig.class);
        User getUser = (User) context.getBean("getUser");

        System.out.println(getUser.getName());
    }
}

静态代理

接口

//租房
public interface Rent {
    public void rent();
}

接口的实现类

// 房东
public class Host implements Rent {
    public void rent() {
        System.out.println("房东要出租房子");
    }
}

生成代理类

// 我们用这个类,自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler{

    //被代理的接口
    private Rent rent;

    public void setRent(Rent rent) {
        this.rent = rent;
    }

    // 生成得到的代理类
    public Object getProxy(){
      return   Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
    }

    //处理代理实例,并返回结果
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        // 动态代理的本质,就是使用反射机制实现
        seeHouse();
        Object result = method.invoke(rent, args);
        fare();

        return result;
    }

    public void seeHouse(){
        System.out.println("中介带我看房");
    }
    public void fare(){
        System.out.println("中介收钱");
    }
}

主方法

public class Client {
    public static void main(String[] args) {
        // 真实角色
        Host host = new Host();
        //代理角色  通过代理类生成并不存在
        ProxyInvocationHandler pih = new ProxyInvocationHandler();

        // 通过调用程序处理角色来处理我们要调用的接口对象
        pih.setRent(host);

        Rent proxy = (Rent) pih.getProxy();

        proxy.rent();

    }
}


AOP

创建接口和接口实现类

方式一:使用原生Spring API接口实现aop
applicationContext.xml

!--注册bean-->
    <bean id="userService" class="com.jie.service.UserServiceImpl"/>
    <bean id="log" class="com.jie.log.Log"/>
    <bean id="afterLog" class="com.jie.log.AfterLog"/>
  <aop:config>
        <!--切入点:expression:表达式:execution(*  要切入的位置.*(..))-->
        <aop:pointcut id="pointcut" expression="execution(*  com.jie.service.UserServiceImpl.*(..))"/>
       <!--执行环绕增强-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
     </aop:config>

方式二:自定义类实现aop
自己定义一个类DiyPiontCut

public class DiyPiontCut {
    public void before(){
        System.out.println("===============方法执行前=============");
    }
    public void after(){
        System.out.println("===============方法执行后=============");
    }
}

配置applicationContext.xml


<!--第二种:自定义类实现aop-->
    <bean id="diy" class="com.jie.diy.DiyPiontCut"/>

    <aop:config>
        <!--自定义切面  ref:要引用的类-->
        <aop:aspect  ref="diy">
            <!--切入点-->
            <aop:pointcut id="point" expression="execution(* com.jie.service.UserServiceImpl.*(..))"/>
            <!--通知-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>
   

方式三:使用注解实现aop
1.新建一个类annocationPointCut

@Aspect// 标注这个类是一个切面
public class AnnocationPointCut {
    @Before("execution(* com.jie.service.UserServiceImpl.*(..))")
    public void bef(){
        System.out.println("=========执行前===========");
    }
    @After("execution(* com.jie.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("=========执行前===========");
    }
}

配置xml文件

  <bean id="annocationPointCut" class="com.jie.diy.AnnocationPointCut"/>

    <!--开启注解支持-->
    <aop:aspectj-autoproxy/>
    

spring、mybatis整合

建立实体类User


@Data
public class User {
    private int id;
    private String name;
    private  String pwd;
}


实现对应接口UserMapper

public interface UserMapper {
    public List<User> getUser();
}

配置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核心配置文件-->
<configuration>
    <!--给实体类取别名-->
    <typeAliases>
        <package name="com.jie.pojo"/>
    </typeAliases>
</configuration>

接口的xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jie.mapper.UserMapper">
    <select id="getUser" resultType="User">
        select * from user
    </select>
</mapper>

配置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
        http://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的配置
        这里使用Spring提供的JDBC:org.springframework.jdbc.datasource.DriverManagerDataSource
    -->
    <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?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>

    </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/jie/mapper/*.xml"/>

    </bean>

    <!--SqlSessionTemplate:就是我们使用的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>


</beans>

接口实现类UserMapperimpl

public class UserMapperImpl implements UserMapper {
    // 我们的所有操作,都使用sqlSession来执行,现在我们都是用SqlSessionTemplate
    private SqlSessionTemplate sqlSession;

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

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

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
        http://www.springframework.org/schema/beans/spring-beans.xsd">

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


<bean id="userMapper" class="com.jie.mapper.UserMapperImpl">
    <property name="sqlSession" ref="sqlSession"/>
</bean>
</beans>

测试类

public class MyTest {
    @Test
    public void test() throws IOException {

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);

        for (User user : userMapper.getUser()) {
            System.out.println(user);
        }


    }

事务声明


    <!--结合AOP实现事务的织入-->
    <!---配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些地方配置事务-->
        <!--配置事务的传播特性 propagation = "" -->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!--配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.jie.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值