基于注解的Spring框架--通过Spring框架管理对象
1.1JavaConfig
使用 Java 类作为xml配置文件的替代 ,在这个 Java 类中可以创建 Java 对象,把对象放入 Spring 容器中 (注入到容器)
使用两个注解 :
-
@Configuration :放在一个类的上面 ,表示这个类是作为配置文件使用的
-
@Bean : 声明对象 ,把对象注入到容器中
/**
* Configuration : 表示当前类是作为配置文件使用的 。就是用来配置容器的
* 位置 : 在类的上面
* SpringConfig 这个类就相当于 spring.xml ,相当于spring的配置文件 。
*/
@Configuration
public class SpringConfig {
/**
* 创建方法 ,方法的返回值是对象。在方法上面加入 @Bean注释
* 方法的返回值就注入到容器中了
*
* @Bean 把返回值对象注入到Spring容器中。相当于<bean></bean>
* 位置 : 在方法上面
* 说明 : @Bean,不指定对象的名称 ,默认方法名就是对象的id ,
* 也就相当于 <bean id="createStudent"><bean/>
*/
@Bean
public Student aaa(){
Student student = new Student();
student.setSid(1);
student.setSname("zhangsan");
student.setAge(23);
return student;
}
/***
* 指定对象在容器中的名称(指定<bean>的id属性)
* @Bean的name属性,指定对象的名称(id)
*/
@Bean(name = "lisiStudent")
public Student makeStudent(){
Student s2 = new Student();
s2.setSname("李四");
s2.setAge(22);
s2.setSid(3);
return s2;
}
}
测试类
public class SpringConfigTest {
@Test
public void testCreateStudent(){
// 1. 加载Spring的配置类,获取Spring容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
// 2. 从Spring容器中获取对象 aaa:这个是方法名 ,Student.class:这个是获取对象的返回值类型
Student student = applicationContext.getBean("aaa", Student.class);
// 3. 测试/检查从容器中获取的对象
System.out.println(student);
// 3. 关闭/释放资源
applicationContext.close();
}
}
1.2 @ImportResource
@ImportResource 作用导入其他 XML 配置文件 ,等于在 XML 配置了 import 标签
<import resource="其他配置文件" />
1.3读取.properties配置文件
首先,在src/main/resources下创建jdbc.properties文件,并添加一些配置:
url=jdbc:mysql://localhost:3306/database driver=com.mysql.jdbc.Driver
然后,在com.dongsheng.spring
包下创建JdbcProperties
类,在类中声明private String url;
和private String driver;
这2个属性,它们的值将来自配置文件中配置的值,可以在属性之前添加@Value
注解来读取配置文件中的值!但是,这个过程应该是由Spring框架来实现的,也就是说,将由Spring框架为这2个属性注入值!
如果由Spring框架注入这2个属性值,前提是Spring框架会管理JdbcProperties
类的对象!所以,应该先创建一个配置类,在配置类中指定组件扫描JdbcProperties
类所在的包!则创建SpringConfig
类:
@Configuration
@ComponentScan("com.dongsheng.spring")
public class SpringConfig {
}
后续,当加载这个SpringConfig
配置类时,Spring框架就会扫描com.dongsheng.spring
这个包,就能够发现JdbcProperties
类,当然,如果需要Spring框架管理这个类的对象,在类的声明之前还需要添加@Component
/ @Controller
/ @Service
/ @Repository
中的某1个注解!
并且,还需要在JdbcConfig
类的声明之前通过@PropertySource
注解来指定需要读取的配置文件是哪一个文件!
所以,关于JdbcProperties
类的代码:
@Component
@PropertySource("jdbc.properties")
public class JdbcProperties {
@Value("${url}")
private String url;
@Value("${driver}")
private String driver;
}
完成后,就可以进行测试了:
@Test
public void testJdbcProperties(){
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
JdbcProperties jdbcProperties = ac.getBean("jdbcProperties", JdbcProperties.class);
System.out.println(jdbcProperties);
ac.close();
}
注意:在编写配置文件时,不要轻易使用username
作为配置属性的名称,如果使用了,最终项目运行在Windows操作系统中时,读取到的会是当前登录Windows操作系统的系统用户的名称,而不是配置文件中配置的值!