Spring学习笔记-2

Spring相关API

ApplicationContext的实现类

  1. ClassPathXmlApplicationContext
  • 从类的根目录下加载配置文件,推荐使用
  1. FileSystemXmlApplicationContext
  • 从磁盘路径上加载配置文件,配置文件可以在磁盘的任意位置
  1. AnnotationConfigApplicationContext
  • 使用注解配置容器对象时,需要使用此类来创建Spring容器,它用来读取注解

getBean()方法使用

//通过id匹配
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao1 = (UserDao) app.getBean("userDao");

//通过字节码对象匹配
UserDao userDao = app.getBean(UserDao.class);

Spring配置数据源

导入数据源坐标和数据库驱动坐标
<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency>

        <dependency>
            <groupId>org.apache.servicemix.bundles</groupId>
            <artifactId>org.apache.servicemix.bundles.c3p0</artifactId>
            <version>0.9.5.5_1</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>
创建数据源对象
<context:property-placeholder location="classpath:jdbc.properties"/><!--加载外部properties文件-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
设置数据源的基本连接数据
jdbc.driver=com.mysql.jdbc.cj.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root
使用数据源获取连接资源和归还连接资源
public class DataSourceTest {

    @Test
    //测试Spring容器产生数据源对象
    public void test4() throws Exception {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        DataSource dataSource = app.getBean(DataSource.class);
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
}

抽取properties配置文件

<!--抽取properties:
    先引入命名空间:xmlns:context="http://www.springframework.org/schema/context"
         约束路径:http://www.springframework.org/schema/context
                 http://www.springframework.org/schema/spring-context.xsd-->
    <context:property-placeholder location="classpath:jdbc.properties"/><!--加载外部properties文件-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

Spring注解开发(替代配置文件)

Spring原始注解(主要是替代Bean配置)
注解 说明
@Component 使用在类上用于实例化Bean
@Controller 使用在Web层上用于实例化Bean
@Service 使用在service上用于实例化Bean
@Repository 使用在dao上用于实例化Bean
@Autowired 使用在字段上用于根据类型注入依赖
@Qualifier 结合@Autowired一起使用用于根据名称进行依赖注入
@Resource 相当于@Autowired+@Qualifier,按照名称进行注入
@Value 注入普通属性
@Scoop 标准Bean的作用范围
@PostConstruct 使用在方法上标注该方法时Bean的初始化方法
@PreDestory 使用在方法上标注该方法时Bean的销毁方法
原始注解入门
<!--注解开发时需要在配置文件中配置组件扫描,作用时指定哪个包下的Bean需要进行扫描以便识别使用注解配置的类、字段和方法-->
    <context:component-scan base-package="org.example"/>
//@Component("userDao")
@Repository("userDao")//实例化Bean
public class UserDaoImpl implements UserDao {
    @Override
    public void save() {
        System.out.println("Save running....");
    }
}
//@Component("userService")
@Service("userService")
@Scope("singleton")
public class UserServiceImpl implements UserService {

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

//    @Autowired//按照数据类型从Spring容器中进行匹配
//    @Qualifier("userDao")//是按照id值从容器中进行匹配,但此处@Qualifier要结合@Autowired一起使用
    @Resource(name = "userDao")
    private UserDao userDao;

    @Override
    public void save() {
        System.out.println(driver);
        userDao.save();
    }

    @PostConstruct
    public void init(){
        System.out.println("Server对象初始化方法....");
    }

    @PreDestroy
    public void destory(){
        System.out.println("Service对象销毁方法....");
    }
}
//测试
public class UserController {
    public static void main(String[] args){
        ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = app.getBean(UserService.class);
        userService.save();
        app.close();
    }
}
Spring新注解
注解 说明
@Configuration 用于指定当前类是一个Spring配置类,当创建容器时会从该类上加载注解
@ComponentScan 用于指定Spring在初始化时要扫描的包,作用与在Spring的xml配置文件中的 <context:component-scan base-package="org.example"/> 一样
@Bean 使用在方法上,标注将该方法的返回值存储到Spring容器中
@PropertySource 用于加载.properties文件中的配置
@Import 用于导入其他配置类
Spring使用示例
@Configuration//标志该类是Spring核心配置类
@ComponentScan("org.example")//扫描
@Import(DataSourceConfiguration.class)//引入配置类
public class SpringConfiguration {
}
@PropertySource("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("dataSource")//返回值存储到Spring容器
    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 UserController {
    public static void main(String[] args){
//        ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
     
   ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        UserService userService = app.getBean(UserService.class);
        userService.save();
    }
}

Spring集成Junit

  • 让SpringJunit复制创建Spring容器,但是需要将配置文件的名称告诉它

  • 让需要进行测试的Bean直接在测试类中进行注入

Spring集成Junit示例

<!--导入Spring集成Junit坐标-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.3.17</version>
    </dependency>
@RunWith(SpringJUnit4ClassRunner.class) //使用@Runwith注解替换原来的运行期
//@ContextConfiguration("classpath:applicationContext.xml")
@ContextConfiguration(classes = SpringConfiguration.class) //使用@ContextConfiguration指定配置类或配置文件
public class SpringJunitTest {

    @Autowired //使用@Autowired注入需要测试的对象
    private UserService userService;

    @Autowired
    private DataSource dataSource;

    @Test //创建测试方法进行测试
    public void test1() throws SQLException {
        userService.save();
        System.out.println(dataSource.getConnection());
    }
}

Spring集成web环境

示例
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.3.17</version>
    </dependency>
<!--    全局初始化参数-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    
    <!--    配置监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = req.getServletContext();
        WebApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UserService userService = app.getBean(UserService.class);
        userService.save();
    }
}
posted @ 2022-04-05 22:43  YL_Hello  阅读(21)  评论(0编辑  收藏  举报