Spring中提供新的注解
,用来解决那些类不是我们自己创建的
,但却想要通过注解的方式来管理
1.需要自己写一个类
类的目的是与之前配置文件的目的一致,告知Spring加载初始化的时候该如何创建,管理对象
2.需要在自定义类的上面添加一个描述
添加@Configuration,告知Spring这个类是我的配置,需要让他干活
3.创建BeanFactory工厂
TestMain
package test;
import configclass.ConfigClass;
import controller.StudentController;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestMain {
public static void main(String[] args) {
//通过扫描注解的方式获取一个工厂对象,改变创建工厂的类
BeanFactory factory=new AnnotationConfigApplicationContext(ConfigClass.class);
StudentController controller=(StudentController) factory.getBean("studentController");
System.out.println(controller);
controller.contollerMethod("男");
}
}
4.自己创建的类中会设计方法
方法是用来创建bean对象 对象通常是别人写好的类型 (例如JdbcTemplate
)
方法上面添加@Bean
如果bean注解中不写id 方法名字就是对象的默认id
5.如果自己写的类中除了自定义方法
还需要告知Spring需要扫描其他包
在自己类上面添加一个注解@ComponentScan(value={} | basePackages={})
6.如果在自己类中创建对象需要一些动态的参数
,可以使用外部配置文件的方式引入
工程内创建一个文件 .properties
在当前主配置类中添加注解
@PropertySource(“classpath:xxx.properties”)
可以在配置类中添加属性
,属性以@Value(“${key}”)
ConfigClass
package configclass;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
/**
* 这个类的目的是用来替代原来Spring核心文件背后的目的
* 原来:核心文件---加载文件中的类名字---反射创建对象
* 现在:通过这个自定义类创建对象
* 通过这个类中自定义方法,实现创建对象
*/
@Configuration//告知Spring这个类是我的配置,需要让他干活
@ComponentScan(basePackages = {"controller","service","dao","domain"})//告知Spring需要扫描其他包
@PropertySource("classpath:jdbc.properties")//告知引入文件
public class ConfigClass {//类的目的是与之前配置文件的目的一致,告知Spring加载初始化的时候该如何创建,管理对象
@Value("${driverClassName}")
private String driverClassName;
@Value("${url}")
private String url;
@Value("${jdbcusername}")
private String username;
@Value("${password}")
private String password;
//定义一个方法,目的是获取一个对象 jdbcTemplate
@Bean(value = "jdbcTemplate")
public JdbcTemplate createJdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
//再定义一个方法,获取一个DataSource类型的对象
@Bean(value = "dataSource")
public DataSource createDataSource(){
DriverManagerDataSource dataSource=new DriverManagerDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}
jdbc.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/newtest?useSSL=false&characterEncoding=UTF-8
jdbcusername=root
password=cy414ljh212,,,
7.如果主配置中方法过多
,且方法之间有些没有必然关联
,可以将主配置类拆开
变成多个小配置类
,在主配置类中通过@Import(小配置类.class)进行引入