注解的IOC

基于注解的IOC配置

写在最前
学习基于注解的IoC配置,大家脑海里首先得有一个认知,即注解配置和xml配置要实现的功能都是一样的,都是要降低程序间的耦合。只是配置的形式不一样。
关于实际的开发中到底使用xml还是注解,每家公司有着不同的使用习惯。所以这两种配置方式我们都需要掌握。

环境搭建

第一步:拷贝必备jar包到工程的lib目录。
注意:在基于注解的配置中,我们还要多拷贝一个aop的jar包。如下图:
第二步:在类的根路径下创建一个任意名称的xml文件(不能是中文)
基于注解整合时,导入约束时需要多导入一个context名称空间下的约束。给配置文件导入约束:

<?xml version="1.0" encoding="UTF-8"?><!-- 导入schema约束的位置在:    ..\spring-framework-4.2.4.RELEASE\docs\spring-framework-reference\html\xsd-configuration.html  
  文件中。注意:要导入schema约束-->
  <beans xmlns="http://www.springframework.org/schema/beans"      
  xmlns:context="http://www.springframework.org/schema/context"       
  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                
  http://www.springframework.org/schema/context                 
  http://www.springframework.org/schema/context/spring-context.xsd "></beans>

第三步:使用@Component注解配置管理的资源/** * 客户的业务层实现类 * @author zhy *@Component(value=“customerService”)public class CustomerServiceImpl implements ICustomerService { @Override public void saveCustomer() { System.out.println(“执行了保存客户”); }
第四步在spring的配置文件中开启spring对注解ioc的支持 <context:component-scan base-package=“com.itheima”></context:component-scan>

常用注解用于创建对象的 相当于:

@Component作用: 把资源让spring来管理。相当于在xml中配置一个bean。位置:类上面属性:value:指定bean的id。如果不指定value属性,默认bean的id是当前类的类名。首字母小写。
@Controller @Service @Repository
他们三个注解都是针对一个的衍生注解,他们的作用及属性都是一模一样的。他们只不过是提供了更加明确的语义化。
@Controller:一般用于表现层的注解。
@Service:一般用于业务层的注解。
@Repository:一般用于持久层的注解。细节:如果注解中有且只有一个属性要赋值时,且名称是value,value在赋值是可以不写。
用于注入数据的

 相当于:<property name="" ref="">                              <property name="" value="">

@Autowired作用
: 自动按照类型注入。当使用注解注入属性时,set方法可以省略。它只能注入其他bean类型。当有多个类型匹配时,使用要注入的对象变量名称作为bean的id,在spring容器查找,找到了也可以注入成功。找不到就报错。

@Qualifier作用:

在自动按照类型注入的基础之上,再按照Bean的id注入。它在给字段注入时不能独立使用,必须和@Autowire一起使用;但是给方法参数注入时,可以独立使用。属性: value:指定bean的id。

@Resource作用:

直接按照Bean的id注入。它也只能注入其他bean类型。如果没有指定名称或者没有找到名称,会按照类型查找对象属性: name:指定bean的id。

@Value作用:

注入基本数据类型和String类型数据的–> 可以借助spring的el表达式读取properties文件中的属性属性: value:用于指定值

用于改变作用范围的:
相当于:

@Scope作用: 指定bean的作用范围。属性: value:指定范围的值。 取值:singleton prototype request session globalsession

和生命周期相关的:(了解)
相当于:

@PostConstruct作用: 用于指定初始化方法。
@PreDestroy作用: 用于指定销毁方法。
代码示例
业务层代码:/** * 客户的业务层接口 */public interface ICustomerService { /** * 保存客户 * @param customer * */ * void saveCustomer(); } * /** * 客户的业务层实现类 */ * //作用就相当于在xml中配置了一个bean标签,该注解有value属性,含义是bean的id。//不写的时候,默认的id是:当前类名,且首字母小写。即: * customerServiceImpl@Component(value="customerService") * @Scope(value="singleton")public class CustomerServiceImpl implements ICustomerService {// @Autowired * // 自动按照数据类型注入,拿着当前变量的数据类型在spring的容器中找,找到后,给变量赋值。 * // 当有多个类型匹配时,会使用当前变量名称customerDao作为bean的id,继续在容器中找。// 找到了,也能注入成功。找不到就报错。// * @Qualifier(value="customerDao2")//在自动按照类型注入的基础之上,再按照id注入 * @Resource(name="customerDao2")//直接按照bean的id注入 private ICustomerDao customerDao = null; * @Value("com.mysql.jdbc.Driver")//注入基本类型和String类型数据 * private String driver; * @Override * public void saveCustomer() { * System.out.println(driver); * customerDao.saveCustomer(); * }} 持久层代码: /** * 客户的持久层接口 */public interface ICustomerDao { /** * 保存客户 */ void saveCustomer();} /** * 客户的持久层实现类11111111111111111111 */ @Repository("customerDao1") public class CustomerDaoImpl implements ICustomerDao { @Override public void saveCustomer() { System.out.println("保存了客户111111111111111111"); }} /** * 客户的持久层实现类222222222222222222222222 */ @Repository("customerDao2")public class CustomerDaoImpl2 implements ICustomerDao { @Override public void saveCustomer() { System.out.println("保存了客户2222222222222222222"); }} 测试类代码:public class Client { public static void main(String[] args) { //1.获取容器 ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); //2.根据id获取对象 ICustomerService cs = (ICustomerService) ac.getBean("customerService"); cs.saveCustomer(); }} 配置文件:<?xml version="1.0" encoding="UTF-8"?><!-- 我们导入约束时,除了昨天的那部分之外,还要单独导入一个context名称空间 --><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"> <!-- 告知spring框架在通过读取配置文件创建容器时,扫描的包,并根据包中类的注解创建对象--> <context:component-scan base-package="com.itheima"></context:component-scan></beans>

关于Spring注解和XML的选择问题

注解的优势: 配置简单,维护方便(我们找到类,就相当于找到了对应的配置)。XML的优势: 修改时,不用改源码。不涉及重新编译和部署。Spring管理Bean方式的比较:

spring的纯注解配置

待改造的问题我们发现,之所以我们现在离不开xml配置文件,是因为我们有一句很关键的配置:

<context:component-scan base-package=“com.itheima”></context:component-scan>如果他要也能用注解配置,那么我们就可以脱离xml文件了。

使用注解配置要扫描的包

在一个新的类上:/** * 客户的业务层实现类 */@Configuration//表明当前类是一个配置类@ComponentScan(basePackages = “com.itheima”)//配置要扫描的包public class SpringConfiguration {} 那么新的问题又来了,我们如何获取容器呢?public class Client { public static void main(String[] args) { //1.获取容器:由于我们已经没有了xml文件,所以再用读取xml方式就不能用了。 //这时需要指定加载哪个类上的注解 ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class); //2.根据id获取对象 ICustomerService cs = (ICustomerService) ac.getBean(“customerService”); cs.saveCustomer(); }}
新注解说明

@Configuration

作用: 用于指定当前类是一个spring配置类,当创建容器时会从该类上加载注解。获取容器时需要使用AnnotationApplicationContext(有@Configuration注解的类.class)。
属性: value:用于指定配置类的字节码
示例代码:/** * 用于初始化spring容器的配置类 */@Configurationpublic class SpringConfiguration{}

@ComponentScan

作用: 用于指定spring在初始化容器时要扫描的包。作用和在spring的xml配置文件中的:<context:component-scan base-package=“com.itheima”/>是一样的。
属性: basePackages:用于指定要扫描的包。和该注解中的value属性作用一样。

@PropertySource

作用: 用于加载.properties文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到properties配置文件中,就可以使用此注解指定properties配置文件的位置。
属性: value[]:用于指定properties文件位置。如果是在类路径下,需要写上classpath:
示例代码:@PropertySource(“classpath:config/jdbcConfig.properties”)
配置:

public class JdbcConfig {
       @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(name="dataSource")   
                             public DataSource getDataSource(){
                                     BasicDataSource ds = new BasicDataSource();      
                                       ds.setDriverClassName(driver);      
                                         ds.setUrl(url);       
                                          ds.setUsername(username);     
                                             ds.setPassword(password);      
                                               return ds;    }  }jdbc.properties文件:
                                               jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/day44_ee247_springjdbc.username=rootjdbc.password=1234 注意: 
                                                  我们目前上课使用的版本是4.2.4,在spring4.3以前都需要提供一个占位符配置器:   
                                                       PropertySourcesPlaceholderConfigurer   
                                                        而在spring4.3以后,则不需要提供。    提供的方式如下:(在SpringConfiguration或JdbcConfig中配置均可)  
                                                          @Bean 
                                                             public static 
                                                             PropertySourcesPlaceholderConfigurer  
                                                            propertySourcesPlaceholderConfigurer() {
                                                                    
                                                                     return new PropertySourcesPlaceholderConfigurer(); 
                                                                        }
@Import

作用: 用于导入其他配置类,在引入其他配置类时,可以不用再写@Configuration注解。当然,写上也没问题。
属性: value[]:用于指定其他配置类的字节码。 示例代码:

@Configuration
@ComponentScan(basePackages = "cn.itcast.spring")
@Import({ Configuration_B.class})
public class Configuration_A {}
@Configuration
@PropertySource("classpath:info.properties")
public class Configuration_B { }  
@Bean

作用: 该注解只能写在方法上,表明使用此方法创建一个对象,并且放入spring容器。它就相当于我们之前在xml配置中介绍的factory-bean和factory-method。属性: name:给当前@Bean注解方法创建的对象指定一个名称(即bean的id)。

    示例代码:
    @Bean(name = "datasource2")  
      public DataSource createDS() throws Exception {    
          ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();        comboPooledDataSource.setUser("root");  
                comboPooledDataSource.setPassword("1234");        
                comboPooledDataSource.setDriverClass("com.mysql.jdbc.Driver");      
                  comboPooledDataSource.setJdbcUrl("jdbc:mysql:///spring_ioc");     
                     return comboPooledDataSource;    
                     } 
                     
@Qualifier("")未加:寻找dataSource.若无则报错添加:寻找和"  "之间相同的(功能类似重命名)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值