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;
}
}