spring学习笔记(三)xml与注解结合模式启动

xml与注解结合模式

xml与注解结合模式启动

xml+注解结合模式,xml⽂件依然存在,所以,spring IOC容器的启动仍然从加载xml开始。我们把第三方jar中的bean定义在xml中,把自己开发的bean使用注解。
@Component(“accountDao”),注解加在类上
bean的id属性内容直接配置在注解后⾯如果不配置,默认定义个这个bean的id为类
的类名⾸字⺟⼩写;
另外,针对分层代码开发提供了@Componenet的三种别名@Controller、
@Service、@Repository分别⽤于控制层类、服务层类、dao层类的bean定义,这
四个注解的⽤法完全⼀样,只是为了更清晰的区分⽽已

@Component("connectionUtils")
public class ConnectionUtils {
}
@Repository("accountDao")
public class JdbcAccountDaoImpl implements AccountDao {
}
@Service("transferService")
public class TransferServiceImpl implements TransferService {
}

依赖注入的实现

@AutoWried

@Repository("accountDao")
public class JdbcAccountDaoImpl implements AccountDao {
}

//@Autowired按照类型注入,如果按照类型无法唯一锁定对象,可以结合@Qualifier根据id来使用

@Qualifier

 	@Autowired
    @Qualifier("accountDao")
    private AccountDao accountDao;

纯注解模式

主要涉及注解

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

web.xml配置

<!--告诉ContextLoaderListener配置注解启动-->
  <context-param>
    <param-name>contextInitializerClasses</param-name>
    <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
  </context-param>
  <!--配置启动类的全限定类名-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>com.lagou.edu.SpringConfig</param-value>
  </context-param>
  <!--使用监听器启动springIOC容器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

启动配置类

//@Configuration标识其为spring启动配置类
@Configuration
@ComponentScan({"com.lagou.edu"})
@PropertySource({"classpath:jdbc.properties"})
public class SpringConfig {
    @Value("${jdbc.driver}")
    private String driverClass;
    @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(driverClass);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值