栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring框架IOC实现方式——纯注解 方式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring框架IOC实现方式——纯注解 方式

1、创建配置类SpringConfig
import javax.sql.DataSource;

@Configuration
@ComponentScan("com.sp.study")
@PropertySource({"classpath:jdbc.properties"})
public class SpringConfig {

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

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

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

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

    @Bean("dataSource")
    public DataSource createDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driverrClassName);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }
}

注解解释:

  • @Configuration ,表名当前类是⼀个配置类;
  • @ComponentScan, 注解,替context:component-scan,需要扫描的包;
  • @PropertySource,引⼊外部属性配置⽂件(如:jdbc.properties);
  • @Import ,引⼊其他配置类;
  • @Value ,对变量赋值,可以直接赋值,也可以使⽤ ${} 读取资源配置⽂件中的信息;
  • @Bean ,将⽅法返回对象加⼊ SpringIOC 容器。
2、启动

javaEE

@Test
public void testIoCAnno() throws Exception {
    //通过配置类来启动容器
    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
    //测试
    AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");
    System.out.println(accountDao);
}

Java web


  Archetype Created Web Application

  
  
    contextClass
    
      org.springframework.web.context.support.AnnotationConfigWebApplicationContext
    
  

  
  
    contextConfigLocation
    
    com.sp.study.SpringConfig
  
  
  
    org.springframework.web.context.ContextLoaderListener
  


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/855200.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号