SSM2.2【Spring:Spring注解开发】

Spring原始注解

1
Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率。

 

 

复制代码
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xsi:schemaLocation="
 6        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 7        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 8 
 9 
10     <bean id="dataSource_c3p0" class="com.mchange.v2.c3p0.ComboPooledDataSource">
11         <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
12         <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
13         <property name="user" value="root"></property>
14         <property name="password" value="root"></property>
15     </bean>
16 
17     <!--加载外部的properties文件-->
18     <!--需要在顶部beans中配置命名空间context,并在xsi中添加对应的约束路径-->
19     <context:property-placeholder location="classpath:jdbc.properties"/>
20     <bean id="dataSource_druid" class="com.alibaba.druid.pool.DruidDataSource">
21         <property name="driverClassName" value="${jdbc.driver}"></property>
22         <property name="url" value="${jdbc.url}"></property>
23         <property name="username" value="${jdbc.username}"></property>
24         <property name="password" value="${jdbc.password}"></property>
25     </bean>
26 
27 
28     <!--<bean id="userDao" class="com.haifei.dao.impl.UserDaoImpl"></bean>-->
29     <!--<bean id="userService" class="com.haifei.service.impl.UserServiceImpl">-->
30         <!--<property name="userDao" ref="userDao"></property>-->
31     <!--</bean>-->
32 
33     <!--配置组件扫描-->
34     <!--使用注解进行开发时(代替配置bean方式开发),需要在applicationContext.xml中配置组件扫描,
35     作用是指定哪个包及其子包下的Bean需要进行扫描以便识别使用注解配置的类、字段和方法
36     不配置这个的话,运行会报异常NoSuchBeanDefinitionException-->
37     <context:component-scan base-package="com.haifei" />
38 
39 </beans>
复制代码
1 package com.haifei.dao;
2 
3 public interface UserDao {
4 
5     public void save();
6 }
复制代码
 1 package com.haifei.dao.impl;
 2 
 3 import com.haifei.dao.UserDao;
 4 import org.springframework.stereotype.Component;
 5 import org.springframework.stereotype.Repository;
 6 
 7 //<bean id="userDao" class="com.haifei.dao.impl.UserDaoImpl"></bean>
 8 //@Component("userDao")
 9 @Repository("userDao")
10 public class UserDaoImpl implements UserDao {
11 
12     @Override
13     public void save() {
14         System.out.println("UserDaoImpl: save running...");
15     }
16 }
复制代码
1 package com.haifei.service;
2 
3 public interface UserService {
4 
5     public void save();
6 }
复制代码
 1 package com.haifei.service.impl;
 2 
 3 import com.haifei.dao.UserDao;
 4 import com.haifei.dao.impl.UserDaoImpl;
 5 import com.haifei.service.UserService;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.beans.factory.annotation.Qualifier;
 8 import org.springframework.beans.factory.annotation.Value;
 9 import org.springframework.context.annotation.Scope;
10 import org.springframework.stereotype.Component;
11 import org.springframework.stereotype.Service;
12 
13 import javax.annotation.PostConstruct;
14 import javax.annotation.PreDestroy;
15 import javax.annotation.Resource;
16 
17 //<bean id="userService" class="com.haifei.service.impl.UserServiceImpl"></bean>
18 //@Component("userService")
19 @Service("userService")
20 @Scope("prototype") //默认(不设置时也是)是singleton单例;可以设置为prototype多例
21 public class UserServiceImpl implements UserService {
22 
23     //<property name="userDao" ref="userDao"></property>
24     /*@Autowired //按照数据类型从Spring容器中进行匹配的(只写Autowired,不写Qualifier,也能注入)
25 //    @Qualifier("userDao") //是按照id值从容器中进行匹配的 但是主要此处@Qualifier结合@Autowired一起使用*/
26     @Resource(name="userDao") //@Resource相当于@Qualifier+@Autowired
27     private UserDao userDao;
28 
29     /*public void setUserDao(UserDao userDao) {
30         this.userDao = userDao;
31     }*/
32     /*
33     通过xml配置bean的方式开发时:
34         如果使用set进行依赖注入,则set方法必须有,不能省略
35     通过注解的方式开发时:
36         set方法可以省略,因为注解可以通过反射给userDao赋值
37      */
38 
39 
40     //通过注解注入普通数据类型
41     @Value("itcast")
42     private String heima; // private String heima = "itcast"
43     @Value("${jdbc.driver}") //通过键从jdbc.properties中获取值
44     private String driver;
45 
46 
47     @Override
48     public void save() {
49         System.out.println(heima); //itcast
50         System.out.println(driver); //com.mysql.jdbc.Driver
51         userDao.save();
52     }
53 
54 
55     @PostConstruct
56     public void init(){
57         System.out.println("UserServiceImpl: 初始化方法");
58     }
59     @PreDestroy
60     public void destory(){
61         System.out.println("UserServiceImpl: 销毁方法");
62     }
63 }
复制代码
复制代码
 1 package com.haifei.web;
 2 
 3 import com.haifei.service.UserService;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.context.support.ClassPathXmlApplicationContext;
 6 import org.springframework.stereotype.Controller;
 7 
 8 /**
 9  * 假的servlet
10  * 用于测试
11  */
12 //@Controller
13 public class UserController {
14 
15     public static void main(String[] args) {
16 //        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
17         ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
18         UserService userService = app.getBean(UserService.class);
19         userService.save();
20         app.close();
21 
22         /*
23             UserServiceImpl: 初始化方法
24             itcast
25             com.mysql.jdbc.Driver
26             UserDaoImpl: save running...
27             七月 15, 2021 7:37:53 下午 org.springframework.context.support.AbstractApplicationContext doClose
28             信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@e2144e4: startup date [Thu Jul 15 19:37:52 CST 2021]; root of context hierarchy
29          */
30     }
31 
32 }
复制代码

Spring新注解

 

 

 1

复制代码
 1 package com.haifei.config;
 2 
 3 import com.alibaba.druid.pool.DruidDataSource;
 4 import com.mchange.v2.c3p0.ComboPooledDataSource;
 5 import org.springframework.beans.factory.annotation.Value;
 6 import org.springframework.context.annotation.Bean;
 7 import org.springframework.context.annotation.ComponentScan;
 8 import org.springframework.context.annotation.Configuration;
 9 import org.springframework.context.annotation.PropertySource;
10 
11 import javax.sql.DataSource;
12 import java.beans.PropertyVetoException;
13 
14 @Configuration //标志该类是Spring的核心配置类
15 @ComponentScan("com.haifei") //组件扫描<context:component-scan base-package="com.haifei" />
16 @PropertySource("classpath:jdbc.properties")//加载外部的properties文件<context:property-placeholder location="classpath:jdbc.properties"/>
17 public class SpringConfiguration {
18 
19     @Bean("dataSource1") //Spring会将当前方法的返回值以指定名称dataSource1存储到Spring容器中
20     public DataSource getDataSource1() throws PropertyVetoException {
21         ComboPooledDataSource dataSource = new ComboPooledDataSource();
22         dataSource.setDriverClass("com.mysql.jdbc.Driver");
23         dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
24         dataSource.setUser("root");
25         dataSource.setPassword("root");
26         return dataSource;
27     }
28 
29     @Value("${jdbc.driver}")
30     private String driver;
31     @Value("${jdbc.url}")
32     private String url;
33     @Value("${jdbc.username}")
34     private String username;
35     @Value("${jdbc.password}")
36     private String password;
37 
38     @Bean("dataSource2")
39     public DataSource getDataSource2() {
40         DruidDataSource dataSource = new DruidDataSource();
41         dataSource.setDriverClassName(driver);
42         dataSource.setUrl(url);
43         dataSource.setUsername(username);
44         dataSource.setPassword(password);
45         return dataSource;
46     }
47 
48 }
复制代码

2

复制代码
 1 package com.haifei.config;
 2 
 3 import com.alibaba.druid.pool.DruidDataSource;
 4 import com.mchange.v2.c3p0.ComboPooledDataSource;
 5 import org.springframework.beans.factory.annotation.Value;
 6 import org.springframework.context.annotation.*;
 7 
 8 import javax.sql.DataSource;
 9 import java.beans.PropertyVetoException;
10 
11 @Configuration //标志该类是Spring的核心配置类
12 @ComponentScan("com.haifei") //组件扫描<context:component-scan base-package="com.haifei" />
13 @Import(DataSourceConfiguration.class)//引入其他配置文件(分模块开发)<import resource="" />   {xxx.class,yyy.class}
14 public class SpringConfiguration {
15 
16     /*@Bean("dataSource1") //Spring会将当前方法的返回值以指定名称dataSource1存储到Spring容器中
17     public DataSource getDataSource1() throws PropertyVetoException {
18         ComboPooledDataSource dataSource = new ComboPooledDataSource();
19         dataSource.setDriverClass("com.mysql.jdbc.Driver");
20         dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
21         dataSource.setUser("root");
22         dataSource.setPassword("root");
23         return dataSource;
24     }*/
25 
26 }
复制代码
复制代码
 1 package com.haifei.config;
 2 
 3 import com.alibaba.druid.pool.DruidDataSource;
 4 import org.springframework.beans.factory.annotation.Value;
 5 import org.springframework.context.annotation.Bean;
 6 import org.springframework.context.annotation.PropertySource;
 7 
 8 import javax.sql.DataSource;
 9 
10 @PropertySource("classpath:jdbc.properties")//加载外部的properties文件<context:property-placeholder location="classpath:jdbc.properties"/>
11 public class DataSourceConfiguration {
12 
13     @Value("${jdbc.driver}")
14     private String driver;
15     @Value("${jdbc.url}")
16     private String url;
17     @Value("${jdbc.username}")
18     private String username;
19     @Value("${jdbc.password}")
20     private String password;
21 
22     @Bean("dataSource2")
23     public DataSource getDataSource2() {
24         DruidDataSource dataSource = new DruidDataSource();
25         dataSource.setDriverClassName(driver);
26         dataSource.setUrl(url);
27         dataSource.setUsername(username);
28         dataSource.setPassword(password);
29         return dataSource;
30     }
31 
32 }
复制代码
复制代码
 1 package com.haifei.web;
 2 
 3 import com.haifei.config.SpringConfiguration;
 4 import com.haifei.service.UserService;
 5 import org.springframework.context.ApplicationContext;
 6 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 7 import org.springframework.context.support.ClassPathXmlApplicationContext;
 8 import org.springframework.stereotype.Controller;
 9 
10 /**
11  * 假的servlet
12  * 用于测试
13  */
14 //@Controller
15 public class UserController {
16 
17     public static void main(String[] args) {
18 /*//        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
19         ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
20         UserService userService = app.getBean(UserService.class);
21         userService.save();
22         app.close();*/
23         /*
24             UserServiceImpl: 初始化方法
25             itcast
26             com.mysql.jdbc.Driver
27             UserDaoImpl: save running...
28             七月 15, 2021 7:37:53 下午 org.springframework.context.support.AbstractApplicationContext doClose
29             信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@e2144e4: startup date [Thu Jul 15 19:37:52 CST 2021]; root of context hierarchy
30          */
31 
32 
33         ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
34         UserService userService = app.getBean(UserService.class);
35         userService.save();
36         /*
37         UserServiceImpl: 初始化方法
38         itcast
39         com.mysql.jdbc.Driver
40         UserDaoImpl: save running...
41          */
42     }
43 
44 }
复制代码
posted @   yub4by  阅读(56)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示