@ComponentScan 设置扫描的文件包,使得包含的注解能起作用
@Component 把资源让spring来管理。相当于在xml中配置一个bean。
value:指定bean的id。如果不指定value属性,默认bean的id是当前类的类名。首字母小写
@Controller 与@Component作用一致,但一般用于表现层的注解
@Service 与@Component作用一致,但一般用于业务层的注解
@Repository 与@Component作用一致,但一般用于持久层的注解@Autowired 自动按照类型注入。当使用注解注入属性时,set方法可以省略。先按照类型匹配注入。 当有多个类型匹配时,使用要注入的对象变量名称作为bean的id,在spring容器查找,找到了也可以注入成功。找不到就报错
@Qualifier 在自动按照类型注入的基础之上,再按照Bean的id注入。它在给字段注入时不能独立使用,必须和@Autowire一起使用;但是给方法参数注入时,可以独立使用。
@Resource 直接按照Bean的id注入。它也只能注入其他bean类型。先ofName再ofType
@Value 注入基本数据类型和String类型数据的 value:用于指定值@Scope 指定bean的作用范围。 value:singleton prototype request session globalsession
@PostConstruct 用于指定初始化方法。(在构造方法之后立即执行)
@PreDestroy 用于指定销毁方法。(在销毁对象之前调用)@ComponentScan 用于指定spring在初始化容器时要扫描的包。
Spring整合Junit
@Bean 该注解只能写在方法上,表明使用此方法创建一个对象,并且放入spring容器。
@import 用于导入其他配置类,在引入其他配置类时,可以不用再写@Configuration注解。
@Configuration 用于指定当前类是一个spring配置类,当创建容器时会从该类上加载注解
@PropertySource 用于加载.properties文件中的配置。@RunWith --@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration@ContextConfiguration注解:
locations属性:用于指定配置文件的位置。如果是类路径下,需要用classpath:表明
classes属性:用于指定注解的类。当不使用xml配置时,需要用此属性指定注解类的位置。
@Component
@Controller
@Service
@Repository
@Autowired
以上标签可以将下面xml配置中的标签配置
等同于设置以下注解
@Service("accountService")//创建service对象,并存储在容器中,id名为accountService public class AccountServiceImpl implements AccountService { @Autowired//自动注入依赖 优先type,匹配dao实现类注入 private AccountDao accountDao; @Override public List getAccounts() { return accountDao.selectAllAccounts(); } }
@Configuration
@Value
@PropertySource
@Bean
的使用:
@Configuration//标记为配置文件类 @PropertySource("jdbc.properties")//交给spring读取properties public class JdbcXml { @Value("${driverClass}") private String driverClass; @Value("${url}") private String url; @Value("${user}") private String user; @Value("${password}") private String password; @Bean//返回值存储在对象容器中,id为方法名 public DataSource dataSource() throws PropertyVetoException { ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setDriverClass(driverClass); dataSource.setJdbcUrl(url); dataSource.setUser(user); dataSource.setPassword(password); return dataSource; } }
@RunWith @ContextConfiguration
单元测试
@RunWith(SpringJUnit4ClassRunner.class)// @ContextConfiguration(classes = BeanXml.class) public class TestAccount { @Autowired private AccountService accountService; //使用spring单元测试 @Test public void testAccount2(){ List accounts = accountService.getAccounts(); System.out.println(accounts); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)