Spring_新注解
使用Spring原始注解还不能全部代替xml配置文件,还需要使用注解替代的配置如下
- 非自定义的Bena的配置
- 加载properties文件的配置
- 组件扫描配置
- 引入其他文件
新注解
@Configuration | 用于指定当前类是Spring配置类,当创建容器时会从该类上加载注解 |
---|---|
@ComponentScan | 用于指定Spring在初始化容器时要扫描的包 |
@Bean | 使用在方法上,标注将该方法的返回值存储到Spring容器中 |
@PropertySource | 用于加载properties文件中的配置 |
@import | 用于导入其他配置类 |
核心配置类(SpringConfiguation.class)
示例
DataSourceConfiguration.class
package com.lzy.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 javax.sql.DataSource;
//加载配置源文件
// <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
@PropertySource("classpath:jdbc.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;
// 取代的xml配置
// <bean id="" class="com.mchange.v2.c3p0.ComboPooledDataSource">
// <property name="driverClass" value="${jdbc.driver}"></property>
// <property name="jdbcUrl" value="${jdbc.url}"></property>
// <property name="user" value="${jdbc.username}"></property>
// <property name="password" value="${jdbc.password}"></property>
// </bean>
//Spring 会将当前方法的返回值以指定名称存储到Spring容器中
@Bean("dataSource")
public DataSource getDataSource() throws Exception {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
}
SpringConfiguration.class
package com.lzy.config;
import org.springframework.context.annotation.*;
//Spring 核心配置类
@Configuration
//<context:component-scan base-package="com.lzy"></context:component-scan>
@ComponentScan("com.lzy")
// <import resource="">
@Import(DataSourceConfiguration.class)
public class SpringConfiguration {
}
main
package com.lzy.web;
import com.lzy.config.SpringConfiguration;
import com.lzy.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserController {
public static void main(String[] args){
//ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
UserService userService = (UserService)app.getBean("userService");
userService.save();
}
}