spring注解 spring 原始注解 1.1 @Component注解 1.2 @Controller,@Service,@Repository同上 1.3 注解方式依赖注入 spring 新注解
spring 原始注解
1.1 @Component注解
< ! -- spring 使用注解创建对象 component- scan 组件扫描器 用来扫描包下面的注解 -- >
< context: component- scan base- package = "com.lovely" / >
利用ClassPathXmlApplicationContext可创建对象
package com. lovely. test;
@Component ( "app" )
public Class App {
}
public static void main ( String[ ] args) { ClassPathXmlApplicationContext application = new ClassPathXmlApplicationContext ( "classpath:applicationContext.xml" ) ; App app = ( App) application. getBean ( "app" ) ;
}
1.2 @Controller,@Service,@Repository同上
1.3 注解方式依赖注入
@Resource private UserDao userDao; @Value ( "${jdbc.driver}" ) private String driver; @Value ( "a simple string..." ) private String str;
spring 新注解
1. 用来解析配置类,利用配置类替代xml
package com. lovely. config; import org. springframework. context. annotation. ComponentScan;
import org. springframework. context. annotation. Configuration;
import org. springframework. context. annotation. Import; @Configuration
@ComponentScan ( "com.lovely" )
@Import ( DataSourceConfiguration. class )
public class SpringConfiguration { }
@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.userPassword}" ) private String password; @Bean ( "druidDataSource" ) public DataSource getDataSource ( ) { DruidDataSource dataSource = new DruidDataSource ( ) ; dataSource. setDriverClassName ( driver) ; dataSource. setUrl ( url) ; dataSource. setUsername ( username) ; dataSource. setPassword ( password) ; System. out. println ( dataSource) ; return dataSource; } }
package com. lovely. web; import com. lovely. config. SpringConfiguration;
import com. lovely. service. UserService;
import org. springframework. context. annotation. AnnotationConfigApplicationContext;
import org. springframework. stereotype. Controller;
@Controller ( "userController" )
public class UserController { public static void main ( String[ ] args) { AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext ( SpringConfiguration. class ) ; UserService user = ( UserService) app. getBean ( "userService" ) ; user. service ( ) ; app. close ( ) ; } }