Spring注解开发
Spring原始注解
Spring原始注解主要是替代\
注解 | 说明 |
---|---|
@Component | 使用在类上用于实例化Bean |
@Controller | 使用在Web层类上用于实例化Bean |
@Service | 使用在Service层类上用于实例化Bean |
@Repository | 使用在dao层类上用于实例化Bean |
@Autowired | 使用在字段上用于根据类型依赖注入 |
@Qualifier | 结合@Autowired一起使用用于根据名称进行依赖注入 |
@Resource | 相当于@Autowired+@Qualifier,按照名称进行注入 |
@Value | 注入普通属性 |
@Scope | 标注Bean的作用范围 |
@PostConstruct | 使用在方法上标注该方法是Bean的初始化方法 |
@PreDestory | 使用在方法上标注该方法是Bean的销毁方法 |
在使用注解进行开发时,需要在applicationContext.xml中配置组件扫描,作用是指定那个包及其子包下的Bean需要进行扫描以便识别使用注解配置的类、字段、方法
<!--配置组件扫描-->
<context:component-scan base-package="基本包"/>
Spring新注解
注解 | 说明 |
---|---|
@Configuration | 用于指定当前类是一个Spring配置类,当创建容器时会从该类上加载注解 |
@ComponentScan | 用于指定Spring在初始化容器时要扫描的包,组件扫描 |
@Bean | 使用在方法上,标注将该方法返回值存储到Spring容器中 |
@PropertySource | 用于加载.properties文件中的配置 |
@Import | 用于导入其他配置类 |
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
/**
* @author: Thorn
* @Date: 2020/9/19 13:21
* @Description:
*/
//声明Spring配置类
@Configuration
//引入Properties配置文件
//<context:property-placeholder location="classpath:mysql.properties" />
@PropertySource("classpath:mysql.properties")
public class DataSourceConfiguration {
//注入方式配置
@Value("${driverClassName}")
private String driver;
@Value("${url}")
private String url;
@Value("${username}")
private String username;
@Value("${password}")
private String password;
@Bean("dataSource") //Spring将当前方法的返回值已指定名称存储到Spring容器中
public DataSource getDataSource(){
DruidDataSource dt = new DruidDataSource();
dt.setDriverClassName(driver);
dt.setUrl(url);
dt.setUsername(username);
dt.setPassword(password);
return dt;
}
}
import org.springframework.context.annotation.*;
/**
* @author: Thorn
* @Date: 2020/9/19 13:08
* @Description:
*/
//标注该类时Spring的核心配置类
@Configuration
//组件扫描
@ComponentScan("java")
//引入Spring配置文件,可以是数组类型{xx.class,aa.class}
@Import(DataSourceConfiguration.class)
public class SpringConfiguration {
}
import com.alibaba.druid.pool.DruidDataSource;
import config.SpringConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.sql.Connection;
import java.sql.SQLException;
/**
* @author: Thorn
* @Date: 2020/9/17 20:52
* @Description:
*/
public class DruidUtils {
//导入配置文件类,括号填写类名.class
private static ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
private static DruidDataSource dt(){
return (DruidDataSource) app.getBean("dataSource");
}
public static Connection getConnect() throws SQLException {
return dt().getConnection();
}
}