1. 使用注解配置Spring入门
1.1 相关jar包
在基于注解的配置中,我们还要多拷贝一个aop的jar包
1.2 创建目录和xml文件
基于注解整合时,Spring配置文件导入约束时需要多导入一个context名称空间下的约束。
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns = " http://www.springframework.org/schema/beans"
xmlns: p= " http://www.springframework.org/schema/p"
xmlns: context= " http://www.springframework.org/schema/context"
xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance"
xsi: schemaLocation= " http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
" >
</ beans>
1.3 创建服务类
创建一个测试的服务类,并且加入使用@Component注解,声明该类允许注入到Spring容器。
public class CustomerService {
public void save ( ) {
System. out. println ( "-保存数据-" ) ;
}
}
1.4 在spring的配置文件中加入扫描注解
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns = " http://www.springframework.org/schema/beans"
xmlns: p= " http://www.springframework.org/schema/p"
xmlns: context= " http://www.springframework.org/schema/context"
xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance"
xsi: schemaLocation= " http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" >
< context: component-scan base-package = " cn.zj.spring" > </ context: component-scan>
</ beans>
1.5 调用测试代码
public class CustomerServiceTest {
public static void main ( String[ ] args) {
ClassPathXmlApplicationContext context= new ClassPathXmlApplicationContext ( "classpath:applicationContext.xml" ) ;
CustomerService customerService = context. getBean ( "customerService" , CustomerService. class ) ;
customerService. save ( ) ;
context. close ( ) ;
}
}
2. Spring常用注解说明
2.1 IOC常用注解以及说明
@Component
@Scope ( "singleton" )
public class HelloService {
public void say ( ) {
System. out. println ( "hello service" ) ;
}
@PostConstruct
public void initMethod ( ) {
System. out. println ( "初始化方法...." ) ;
}
@PreDestroy
public void destory ( ) {
System. out. println ( "销毁方法..." ) ;
}
}
2.2 DI注解以及说明
@Controller
public class CustomerServlet {
@Autowired
@Qualifier ( "customerService02" )
private CustomerService customerService;
public void say ( ) {
customerService. say ( ) ;
}
}
3. Spring综合案例(注解)-模拟注册功能
UserDaoImpl.java
public class UserDaoImpl implements UserDao {
@Autowired
private DataSource dataSource;
@Override
public boolean register ( User user) {
try {
Connection conn = dataSource. getConnection ( ) ;
System. out. println ( conn) ;
System. out. println ( user) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
return true ;
}
}
UserServiceImpl.java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public boolean register ( User user) {
return userDao. register ( user) ;
}
}
UserServlet.java
@Controller
public class UserServlet {
@Autowired
private UserService userService;
public void register ( User user) {
userService. register ( user) ;
}
}
UserServletTest.java
public class UserServletTest {
@Test
public void register ( ) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext ( "applicationContext.xml" ) ;
UserServlet userServlet = context. getBean ( "userServlet" , UserServlet. class ) ;
User user = new User ( "xiaoxiao" , "666" , 18 ) ;
userServlet. register ( user) ;
}
}
4. Spring纯注解配置
4.1 相关注解
替换XML配置文件的@Configuration注解 @Configuration配置类注解,在纯注解配置中,类加了该注解,就意味着该类是Spring的配置类。该类的功能就是用于替代原来的XML配置文件。作用: 用于指定当前类是一个spring配置类,当创建容器时会从该类上加载注解。获取容器时需要使用AnnotationConfigApplicationContext(有@Configuration注解的类.class)。 @ComponentScan注解 @ComponentScan注解扫描类,作用就是配置扫描Spring组件类的路径。功能等同原来配置文件的–作用: 用于指定spring在初始化容器时要扫描的包。作用和在spring的xml配置文件中的:<context:component-scan base-package=“cn.zj.spring”/>是一样的。–属性: basePackages:用于指定要扫描的包。和该注解中的value属性作用一样。 @PropertySource注解 作用: 用于加载.properties文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到properties配置文件中,就可以使用此注解指定properties配置文件的位置。属性: value[]:用于指定properties文件位置。如果是在类路径下,需要写上classpath: @Bean注解 作用: 该注解只能写在方法上,使用此方法创建一个对象,并且放入spring容器。它就相当于我们之前在xml配置中介绍的<bean标签>属性: name:给当前@Bean注解方法创建的对象指定一个名称(即bean的id)。 @Import注解 作用: 用于导入其他配置类,在引入其他配置类时,可以不用再写@Configuration注解。当然,写上也没问题。属性: value[]:用于指定其他配置类的字节码。 @Value注解 读取properties配置文件以后, 使用
k
e
y
获
取
配
置
文
件
中
对
应
的
值
@
V
l
a
u
e
(
“
{key}获取配置文件中对应的值@Vlaue(“
k e y 获 取 配 置 文 件 中 对 应 的 值 @ V l a u e ( “ {jdbc.dirverClassName}”)private String driverClassName;
4.2 纯注解配置
@Configuration
@ComponentScan ( "cn.xiaoxiao" )
@PropertySource ( "db.properties" )
public class SpringConfig {
@Value ( "${jdbc.driverClassName}" )
private String driverClassName;
@Value ( "${jdbc.url}" )
private String url;
@Value ( "${jdbc.username}" )
private String username;
@Value ( "${jdbc.password}" )
private String password;
@Value ( "${jdbc.maxActive}" )
private Integer maxActive;
@Bean ( name = "dataSource" , initMethod = "init" , destroyMethod = "close" )
public DataSource getDataSource ( ) {
DruidDataSource ds = new DruidDataSource ( ) ;
ds. setDriverClassName ( this . driverClassName) ;
ds. setUrl ( this . url) ;
ds. setUsername ( this . username) ;
ds. setPassword ( this . password) ;
ds. setMaxActive ( this . maxActive) ;
return ds;
}
}
5. Spring测试
5.1 传统的测试与Spring测试
传统的测试
存在的问题
每个测试都要重新启动spring容器,启动开销大,测试效率低下; 不应该是测试代码管理spring容器,应该是spring容器在管理测试代码。
5.2 使用Spring测试
导入spring测试的jar包
如果使用Spring方式测试,必须使用两个注解
@RunWith注解:表示先启动Spring容器,把junit运行在Spring容器中 @ContextConfiguration注解:从哪里加载资源文件,默认从src(源目录)下面加载
案例代码
xml
/表示先启动Spring容器,把junit运行在Spring容器中
@RunWith(SpringJUnit4ClassRunner.class)
//表示从哪里加载资源文件,默认从src(源目录)下面加载
@ContextConfiguration("classpath:applicationContext.xml")
纯注解
@RunWith ( SpringJUnit4ClassRunner. class )
@ContextConfiguration ( classes= Spring. class )
6. Spring的JDBC操作
UserServlet.java
@Controller
public class UserServlet {
@Autowired
private UserService userService;
public void register ( User user) {
boolean register = userService. register ( user) ;
System. out. println ( register) ;
}
}
UserServiceImpl.java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public boolean register ( User user) {
return userDao. register ( user) ;
}
}
UserDaoImpl.java
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public boolean register ( User user) {
String sql = "select * from user where name = ? and password = ?" ;
Object[ ] params = { user. getName ( ) , user. getPasword ( ) } ;
this . jdbcTemplate. queryForObject ( sql, params, new RowMapper < User> ( ) {
@Override
public User mapRow ( ResultSet resultSet, int i) throws SQLException {
user. setName ( resultSet. getString ( "name" ) ) ;
user. setPasword ( resultSet. getString ( "password" ) ) ;
user. setAge ( 17 ) ;
return user;
}
} ) ;
System. out. println ( user) ;
if ( user != null) {
return true ;
}
return false ;
}
}
SpringConfig.java
@Configuration
@ComponentScan ( "cn.xiaoxiao" )
@PropertySource ( "db.properties" )
public class SpringConfig {
@Value ( "${jdbc.driverClassName}" )
private String driverClassName;
@Value ( "${jdbc.url}" )
private String url;
@Value ( "${jdbc.username}" )
private String username;
@Value ( "${jdbc.password}" )
private String password;
@Value ( "${jdbc.maxActive}" )
private Integer maxActive;
@Bean ( name = "dataSource" )
public DataSource getDataSource ( ) {
DruidDataSource ds = new DruidDataSource ( ) ;
ds. setDriverClassName ( this . driverClassName) ;
ds. setUrl ( this . url) ;
ds. setUsername ( this . username) ;
ds. setPassword ( this . password) ;
ds. setMaxActive ( this . maxActive) ;
return ds;
}
@Bean
public JdbcTemplate getJdbcTemplate ( ) {
JdbcTemplate jdbcTemplate = new JdbcTemplate ( getDataSource ( ) ) ;
return jdbcTemplate;
}
}
SpringConfigTest.java
public class SpringConfigTest {
@Test
public void getDataSource ( ) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext ( SpringConfig. class ) ;
DataSource dataSource = context. getBean ( "dataSource" , DataSource. class ) ;
Connection connection = null;
try {
connection = dataSource. getConnection ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
System. out. println ( connection) ;
}
}
Spring的JDBC的增删改查方法
private JdbcTemplate jdbcTemplate;
public void setDataSource ( DataSource dataSource) {
this . jdbcTemplate = new JdbcTemplate ( dataSource) ;
}
@Override
public void save ( User user) {
this . jdbcTemplate. update ( "insert into t_user (name,email) values (?,?)" ,
user. getName ( ) , user. getEmail ( ) ) ;
}
@Override
public void delete ( Integer id) {
this . jdbcTemplate. update ( "delete from t_user where id = ?" , id) ;
}
@Override
public void update ( User user) {
this . jdbcTemplate. update ( "update t_user set name = ?,email = ? where id = ?" ,
user. getName ( ) , user. getEmail ( ) , user. getId ( ) ) ;
}
@Override
public User findById ( Integer id) {
String sql = "select * from t_user where id = ?" ;
User user = this . jdbcTemplate. queryForObject ( sql, new Object [ ] { id} , new RowMapper < User> ( ) {
@Override
public User mapRow ( ResultSet rs, int rowNum) throws SQLException {
User user = new User ( ) ;
user. setName ( rs. getString ( "name" ) ) ;
user. setEmail ( rs. getString ( "email" ) ) ;
user. setId ( id) ;
return user;
}
} ) ;
return user;
}
@Override
public List< User> list ( ) {
String sql = "select * from t_user" ;
List< User> users = this . jdbcTemplate. query ( sql, new RowMapper < User> ( ) {
@Override
public User mapRow ( ResultSet rs, int rowNum) throws SQLException {
User user = new User ( ) ;
user. setName ( rs. getString ( "name" ) ) ;
user. setEmail ( rs. getString ( "email" ) ) ;
user. setId ( rs. getInt ( "id" ) ) ;
return user;
}
} ) ;
return users;
}