spring 入门

目录

ioc

DI

快速案例

 集合注入

加载properties文件

 纯注解开发模式

注解开发管理第三方bean


ioc

ioc是控制反转的意思,是一种面向对象编程的设计思想。如果不采用这种思想的话我们需要自己维护对象与对象的依赖关系,很容易造成对象耦合度过高。而ioc则可以解决此问题。

ioc容器本质上是一工厂,它把所用到的javaBean对象放入容器中,在需要时直接从容器中获取。而不需要我们再自己new创建实例对象。

DI

DI是依赖注入的意思,它可以将两个有关系的javaBean对象通过Setter方式进行关联。

快速案例

导入spring坐标

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>spring_01_quickstart1</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
        <java.version>1.8</java.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

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

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

 在resources中创建spring配置类applicationContext.xml配置bean

<?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">

<!--1、导入spring坐标-->

<!--2、配置bean-->
    <bean id="bookDao" class="com.itheima.dao.Impl.BookDaoImpl"/>

    <bean id="bookService" class="com.itheima.service.Impl.BookServiceImpl">
<!--4、配置service与dao的关系-->
        <property name="bookDao" ref="bookDao"/>
    </bean>
</beans>

 DI通过setter方式进行注入

package com.itheima.service.Impl;

import com.itheima.dao.BookDao;
import com.itheima.service.BookService;

public class BookServiceImpl implements BookService {

    //3、DI通过setter方式进行注入
    private BookDao bookDao;

    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }

    public void save() {
        bookDao.save();
        System.out.println("book service save...");
    }
}

package com.itheima;

import com.itheima.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    public static void main(String[] args) {
        // 5、获取IoC容器
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        //6、获取bean
        BookService bookService = (BookService) app.getBean("bookService");
        bookService.save();
    }
}

 集合注入

在applicationContext.xml核心容器中配置

 <bean id="bookDao" class="itheima.dao.Impl.BookDaoImpl">
        <!--数组-->
        <property name="array">
            <array>
                <value>123</value>
                <value>456</value>
                <value>789</value>
            </array>
        </property>
        <!--list集合-->
        <property name="list">
            <list>
                <value>nihao</value>
                <value>我是</value>
                <value>who</value>
            </list>
        </property>
        <!--set集合-->
        <property name="set">
            <set>
               <value>nihao</value>
                <value>nihao1</value>
                <value>Nihao</value>
                <value>nihao</value>
            </set>
        </property>
        <!--map集合-->
        <property name="map">
            <map>
                <entry key="china" value="xian"/>
                <entry key="usa" value="huashengdun"/>
                <entry key="jp" value="dj"/>
            </map>
        </property>
        <!--properties-->
        <property name="properties">
            <props>
                <prop key="china">xian</prop>
                <prop key="usa">huashengdun</prop>
                <prop key="jp">dj</prop>
            </props>
        </property>
    </bean>

加载properties文件

有时候我们需要将一些信息保存在properties文件中,比如jdbc的各种配置:

  • 在pom中添加druid的坐标
   <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>
  • 创建jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db
jdbc.user=root
jdbc.password=mysql
  • 在spring容器中开启新的命名空间:context

  •  使用context空间加载properties文件
 <!--使用context空间加载properties文件-->
    <context:property-placeholder location="classpath:*.properties"/>

  • 在spring容器中配置datasouce bean对象
  • 使用属性占位符${}获得文件信息
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

 纯注解开发模式

  • 创建配置类并表示该类为配置类
package com.itheima.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;

@Configuration//设置该类为配置类
@ComponentScan("com.itheima")//包扫描
@PropertySource("jdbc.properties")//加载properties文件
public class SpringConfig {
}
  • 在类上添加添加注解配置bean

对于@Component注解,还衍生出了其他三个注解@Controller,@Service,@Repository

方便我们后期在编写类的时候能很好的区分出这个类是属于表现层业务层还是数据层的类。

dao层:

package com.itheima.dao.Impl;

import com.itheima.dao.BookDao;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import javax.print.DocFlavor;

@Repository("bookDao")//配置bean
public class BookDaoImpl implements BookDao {

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

    @Value("nihao")
    private String name;

    @Override
    public void save() {
        System.out.println("bookDao..."+name+" "+driver);
    }
}

 Service层:

package com.itheima.service.Impl;

import com.itheima.dao.BookDao;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    @Qualifier("bookDao")
    private BookDao bookDao;

    @Autowired
    private DataSource dataSource;

    @Override
    public void save() {
        bookDao.save();
        System.out.println("bookService..."+dataSource);
    }
}
  •  创建运行类并执行
package com.itheima;

import com.itheima.config.SpringConfig;
import com.itheima.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class App {
    public static void main(String[] args) {
        //加载配置类初始化容器
        ApplicationContext apt =new AnnotationConfigApplicationContext(SpringConfig.class);
        BookService bookService = (BookService) apt.getBean(BookService.class);
        bookService.save();
    }
}

@Autowired:通过类型为引用类型属性设置值

@Qualifier:加入ioc容器中有多种相同类型bean,需要使用该注解通过bean名称为引用类型属性设·                 置值

@Value:为基本数据类型或字符串类型属性设置值

@PropertySource:加载properties文件中的属性值

注解开发管理第三方bean

我们通常把所有第三方bean配置到SpringConfig之外的配置类,这样有利于代码阅读和分类管理

  • 创建JdbcConfig类来管理jdbc配置

 

  • 在该配置类中添加一方法,并在该方法上添加@Bean注解
package com.itheima.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

public class JdbcConfig {
    @Bean
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName("${jdbc.driver}");
        ds.setUrl("${jdbc.url}");
        ds.setUsername("${jdbc.user}");
        ds.setPassword("${jdbc.password}");
        return ds;
    }
}
  • 在Spring的配置类上添加@Import引入该配置类

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值