1.使用原始注解遗留的问题
使用原始注解还不能全部替代xml配置文件,还需要使用注解替代的配置如下;
- 非自定义的Bean的配置:<bean>

- 加载properties文件的配置:<context:property-placeholder>

- 组件扫描的配置:<context:component-scan>

- 引入其他配置xml文件:<import>
在applicationContext.xml中引入


2.Spring新注解


Spring在开发时候,可以一个配置文件都不要了,全注解进行开发

DataSourceConfiguration
package com.company.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import java.beans.PropertyVetoException;
import javax.sql.DataSource;
// 专门负责数据源相关配置
// <context:property-placeholder location="classpath:jdbc_c3p0.properties"/>
@PropertySource("classpath:jdbc_c3p0.properties")
public class DataSourceConfiguration {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
// 让Spring把方法的返回值以指定名称存放到Spring容器中
@Bean("dataSource")
public DataSource getDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
}
SpringConfiguration
package com.company.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
// 标志该类是Spring的核心配置类(不要配置文件,不是意味着不要配置,原来的配置只是用类的方式代替文件,用注解的方式代替标签)
@Configuration
// <context:component-scan base-package="com.company"/>
@ComponentScan("com.company")
// <import resource=""/>
@Import({DataSourceConfiguration.class})
public class SpringConfiguration {
}
UserController
package com.company.web;
import com.company.config.SpringConfiguration;
import com.company.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class UserController {
public static void main(String[] args) {
// ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
// 加载核心配置类
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
UserService userService = applicationContext.getBean(UserService.class);
userService.save();
}
}
此时,不再需要applicationContext.xml这个配置文件了,使用Spring全注解开发
