org.springframework.beans.factory.annotation.Autowired Java Examples

The following examples show how to use org.springframework.beans.factory.annotation.Autowired. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: sdn-rx   Author: neo4j   File: AuditingIT.java    License: Apache License 2.0 8 votes vote down vote up
@Test
void auditingOfModificationShouldWork(@Autowired ImmutableEntityTestRepository repository) {

	ImmutableAuditableThing thing = repository.findById(idOfExistingThing).get();
	thing = thing.withName("A new name");
	thing = repository.save(thing);

	assertThat(thing.getCreatedAt()).isEqualTo(EXISTING_THING_CREATED_AT);
	assertThat(thing.getCreatedBy()).isEqualTo(EXISTING_THING_CREATED_BY);

	assertThat(thing.getModifiedAt()).isEqualTo(DEFAULT_CREATION_AND_MODIFICATION_DATE);
	assertThat(thing.getModifiedBy()).isEqualTo("A user");

	assertThat(thing.getName()).isEqualTo("A new name");

	verifyDatabase(idOfExistingThing, thing);
}
 
Example #2
Source Project: sdn-rx   Author: neo4j   File: ReactiveStringlyTypeDynamicRelationshipsIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test // GH-216
void shouldReadDynamicCollectionRelationships(@Autowired PersonWithRelativesRepository repository) {

	repository.findById(idOfExistingPerson)
		.as(StepVerifier::create)
		.consumeNextWith(person -> {
			assertThat(person).isNotNull();
			assertThat(person.getName()).isEqualTo("A");

			Map<String, List<Pet>> pets = person.getPets();
			assertThat(pets).containsOnlyKeys("CATS", "DOGS");
			assertThat(pets.get("CATS")).extracting(Pet::getName).containsExactlyInAnyOrder("Tom", "Garfield");
			assertThat(pets.get("DOGS")).extracting(Pet::getName).containsExactlyInAnyOrder("Benji", "Lassie");
		})
		.verifyComplete();
}
 
Example #3
Source Project: sdn-rx   Author: neo4j   File: RepositoryIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void saveWithAssignedId(@Autowired ThingRepository repository) {

	assertThat(repository.count()).isEqualTo(21);

	ThingWithAssignedId thing = new ThingWithAssignedId("aaBB");
	thing.setName("That's the thing.");
	thing = repository.save(thing);

	try (Session session = createSession()) {
		Record record = session
			.run("MATCH (n:Thing) WHERE n.theId = $id RETURN n", Values.parameters("id", thing.getTheId()))
			.single();

		assertThat(record.containsKey("n")).isTrue();
		Node node = record.get("n").asNode();
		assertThat(node.get("theId").asString()).isEqualTo(thing.getTheId());
		assertThat(node.get("name").asString()).isEqualTo(thing.getName());

		assertThat(repository.count()).isEqualTo(22);
	}
}
 
Example #4
Source Project: sdn-rx   Author: neo4j   File: RepositoryIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void saveEntityWithSelfReferencesInBothDirections(@Autowired PetRepository repository) {
	Pet luna = new Pet("Luna");
	Pet daphne = new Pet("Daphne");

	luna.setFriends(singletonList(daphne));
	daphne.setFriends(singletonList(luna));

	repository.save(luna);

	try (Session session = createSession()) {
		Record record = session.run("MATCH (luna:Pet{name:'Luna'})-[:Has]->(daphne:Pet{name:'Daphne'})"
			+ "-[:Has]->(luna2:Pet{name:'Luna'})"
			+ "RETURN luna, daphne, luna2").single();

		assertThat(record.get("luna").asNode().get("name").asString()).isEqualTo("Luna");
		assertThat(record.get("daphne").asNode().get("name").asString()).isEqualTo("Daphne");
		assertThat(record.get("luna2").asNode().get("name").asString()).isEqualTo("Luna");
	}
}
 
Example #5
Source Project: sdn-rx   Author: neo4j   File: ReactiveRepositoryIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void loadEntityWithBidirectionalRelationshipFromIncomingSide(@Autowired BidirectionalEndRepository repository) {

	long endId;

	try (Session session = createSession()) {
		Record record = session
			.run("CREATE (n:BidirectionalStart{name:'Ernie'})-[:CONNECTED]->(e:BidirectionalEnd{name:'Bert'}) "
				+ "RETURN e").single();

		Node endNode = record.get("e").asNode();
		endId = endNode.id();
	}

	StepVerifier.create(repository.findById(endId))
		.assertNext(entity -> {
			assertThat(entity.getStart()).isNotNull();
		})
		.verifyComplete();
}
 
Example #6
Source Project: sdn-rx   Author: neo4j   File: ReactiveTypeConversionIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void relatedIdsShouldBeConverted(@Autowired ConvertedIDsRepository repository) {

	ThingWithUUIDID aThing = new ThingWithUUIDID("a thing");
	aThing.setAnotherThing(new ThingWithUUIDID("Another thing"));

	List<ThingWithUUIDID> stored = new ArrayList<>();
	StepVerifier.create(repository.save(aThing))
		.recordWith(() -> stored)
		.expectNextCount(1L)
		.verifyComplete();

	ThingWithUUIDID savedThing = stored.get(0);
	assertThat(savedThing.getId()).isNotNull();
	assertThat(savedThing.getAnotherThing().getId()).isNotNull();

	StepVerifier.create(Flux.concat(repository.findById(savedThing.getId()),
		repository.findById(savedThing.getAnotherThing().getId())))
		.expectNextCount(2L)
		.verifyComplete();
}
 
Example #7
Source Project: mPaaS   Author: lihangqi   File: SwaggerConfig.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 动态产生Docket分组信息
 *
 * @return
 */
@Autowired
public void dynamicConfiguration() {
    ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();

    String systemName = "Microservice PaaS";
    ApiInfoBuilder apiInfoBuilder = new ApiInfoBuilder()
            .description("mPaas前端后端对应接口")
            .version("1.0.1")
            .license("Code Farmer Framework(iByte) Org.");

    Map<String, ModuleMappingInfo> moduleInfo = mappingHelper.getMappingInfos();
    for (Map.Entry<String, ModuleMappingInfo> entry : moduleInfo.entrySet()) {
        beanFactory.registerSingleton(entry.getKey(), new Docket(DocumentationType.SWAGGER_2)
                .groupName(entry.getKey())
                .apiInfo(apiInfoBuilder.title(systemName + NamingConstant.DOT + entry.getKey()).build())
                .select()
                .apis(genSubPackage(entry.getKey()))
                .paths(Predicates.or(PathSelectors.ant(NamingConstant.PATH_PREFIX_DATA + "/**"),
                        PathSelectors.ant(NamingConstant.PATH_PREFIX_API + "/**")))
                .build());
    }
}
 
Example #8
Source Project: sdn-rx   Author: neo4j   File: ReactiveRepositoryIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void findWithPageable(@Autowired ReactivePersonRepository repository) {

	Sort sort = Sort.by("name");
	int page = 0;
	int limit = 1;

	StepVerifier.create(repository.findByNameStartingWith("Test", PageRequest.of(page, limit, sort)))
		.assertNext(person -> assertThat(person).isEqualTo(person1))
		.verifyComplete();


	sort = Sort.by("name");
	page = 1;
	limit = 1;

	StepVerifier.create(repository.findByNameStartingWith("Test", PageRequest.of(page, limit, sort)))
		.assertNext(person -> assertThat(person).isEqualTo(person2))
		.verifyComplete();
}
 
Example #9
Source Project: sdn-rx   Author: neo4j   File: ReactiveTransactionManagerMixedDatabasesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void usingAnotherDatabaseExplicitTx(@Autowired ReactiveNeo4jClient neo4jClient) {

	TransactionalOperator transactionTemplate = TransactionalOperator.create(neo4jTransactionManager);

	Mono<Long> numberOfNodes = neo4jClient.query("MATCH (n) RETURN COUNT(n)").in(DATABASE_NAME).fetchAs(Long.class)
		.one()
		.as(transactionTemplate::transactional);

	StepVerifier
		.create(numberOfNodes)
		.expectErrorMatches(e ->
			e instanceof IllegalStateException && e.getMessage().equals(
				"There is already an ongoing Spring transaction for the default database, but you request 'boom'"))
		.verify();
}
 
Example #10
Source Project: sdn-rx   Author: neo4j   File: RepositoryIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void findAndInstantiateGenericRelationships(@Autowired RelationshipToAbstractClassRepository repository) {

	Inheritance.ConcreteClassA ccA = new Inheritance.ConcreteClassA("cc1", "test");
	Inheritance.ConcreteClassB ccB = new Inheritance.ConcreteClassB("cc2", 42);

	List<Inheritance.SuperBaseClass> things = new ArrayList<>();
	things.add(ccA);
	things.add(ccB);
	Inheritance.RelationshipToAbstractClass thing = new Inheritance.RelationshipToAbstractClass();
	thing.setThings(things);

	repository.save(thing);

	List<Inheritance.RelationshipToAbstractClass> all = repository.findAll();

	assertThat(all.get(0).getThings()).containsExactlyInAnyOrder(ccA, ccB);
}
 
Example #11
Source Project: sdn-rx   Author: neo4j   File: RepositoryIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void limitClauseShouldWork(@Autowired ThingRepository repository) {

	List<ThingWithAssignedId> things;

	things = repository.findTop5ByOrderByNameDesc();
	assertThat(things)
		.hasSize(5)
		.extracting(ThingWithAssignedId::getName)
		.containsExactlyInAnyOrder("name20", "name19", "name18", "name17", "name16");

	things = repository.findFirstByOrderByNameDesc();
	assertThat(things)
		.extracting(ThingWithAssignedId::getName)
		.containsExactlyInAnyOrder("name20");
}
 
Example #12
Source Project: cf-butler   Author: pacphi   File: UsageTask.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public UsageTask(
        UsageService service,
        UsageCache cache,
        ObjectMapper mapper) {
    this.service = service;
    this.cache = cache;
    this.mapper = mapper;
}
 
Example #13
Source Project: mykit-delay   Author: sunshinelyz   File: HealthAutoConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@Autowired(required = false)
@ConditionalOnMissingBean
public HealthIndicator jikexiuHealthIndicator(RedisQueue redisQueue, RedisQueueProperties properties) {
    CompositeHealthIndicator compositeHealthIndicator = new  CompositeHealthIndicator(healthAggregator);
    Map<String, LeaderManager> leaderManagerMap = AppEnvContext.getCtx().getBeansOfType(LeaderManager.class);
    LeaderManager manager = null;
    if (leaderManagerMap != null && !leaderManagerMap.isEmpty()) {
        manager = AppEnvContext.getCtx().getBean(SimpleLeaderManager.class);
    }

    compositeHealthIndicator.addHealthIndicator(Constants.HEALTH_INDICATOR_NAME, new QueueHealthIndicator(redisQueue, manager, properties));
    return compositeHealthIndicator;
}
 
Example #14
Source Project: cf-butler   Author: pacphi   File: DatabaseCreator.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public DatabaseCreator(
	DatabaseClient client,
	ResourceLoader resourceLoader,
	DbmsSettings settings,
	ApplicationEventPublisher publisher) {
	this.client = client;
	this.resourceLoader = resourceLoader;
	this.settings = settings;
	this.publisher = publisher;
}
 
Example #15
Source Project: cf-butler   Author: pacphi   File: OrganizationsTask.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public OrganizationsTask(
		DefaultCloudFoundryOperations opsClient,
        OrganizationService organizationService,
		ApplicationEventPublisher publisher) {
    this.opsClient = opsClient;
    this.organizationService = organizationService;
    this.publisher = publisher;
}
 
Example #16
Source Project: flair-engine   Author: viz-centric   File: StatelessBasicAuthenticationSecurityConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
    for (ApplicationProperties.Authentication.FlairBi.BasicAuthentication.Credentials cred :
        applicationProperties.getAuthentication().getFlairBi().getBasicAuthentication().getCredentials()) {

        String[] roles = Optional.ofNullable(cred.getRoles())
            .filter(x -> !x.isEmpty())
            .map(x -> x.toArray(new String[0]))
            .orElse(new String[]{"ROLE_USER"});
        auth.inMemoryAuthentication()
            .withUser(cred.getUsername())
            .password(cred.getPassword())
            .authorities(roles);
    }
}
 
Example #17
Source Project: cf-butler   Author: pacphi   File: ServiceInstanceDetailConsoleNotifier.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
  public ServiceInstanceDetailConsoleNotifier(
PasSettings appSettings,
TkService tkService) {
this.report = new ServiceInstanceDetailCsvReport(appSettings);
this.util = new TkServiceUtil(tkService);
  }
 
Example #18
Source Project: data-highway   Author: HotelsDotCom   File: LoadingBay.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public LoadingBay(HiveTableAction hiveTableAction, Function<HiveRoad, LanderMonitor> monitorFactory) {
  this.hiveTableAction = hiveTableAction;
  this.monitorFactory = monitorFactory;

  monitors = new HashMap<>();
}
 
Example #19
Source Project: sdn-rx   Author: neo4j   File: ReactiveRelationshipsIT.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This stores the same instance in different relationships
 *
 * @param repository The repository to use.
 */
@Test
void shouldSaveMultipleRelationshipsOfSameInstance(@Autowired MultipleRelationshipsThingRepository repository) {

	MultipleRelationshipsThing p = new MultipleRelationshipsThing("p");
	MultipleRelationshipsThing c = new MultipleRelationshipsThing("c1");
	p.setTypeA(c);
	p.setTypeB(Collections.singletonList(c));
	p.setTypeC(Collections.singletonList(c));

	repository.save(p)
		.map(MultipleRelationshipsThing::getId)
		.flatMap(repository::findById)
		.as(StepVerifier::create)
		.assertNext(loadedThing -> {

			MultipleRelationshipsThing typeA = loadedThing.getTypeA();
			List<MultipleRelationshipsThing> typeB = loadedThing.getTypeB();
			List<MultipleRelationshipsThing> typeC = loadedThing.getTypeC();

			assertThat(typeA).isNotNull();
			assertThat(typeA).extracting(MultipleRelationshipsThing::getName).isEqualTo("c1");
			assertThat(typeB).extracting(MultipleRelationshipsThing::getName).containsExactly("c1");
			assertThat(typeC).extracting(MultipleRelationshipsThing::getName).containsExactly("c1");
		})
		.verifyComplete();

	try (Session session = driver.session()) {

		List<String> names = session.run(
			"MATCH (n:MultipleRelationshipsThing {name: 'p'}) - [r:TYPE_A|TYPE_B|TYPE_C] -> (o) RETURN r, o")
			.list(record -> {
				String type = record.get("r").asRelationship().type();
				String name = record.get("o").get("name").asString();
				return type + "_" + name;
			});
		assertThat(names).containsExactlyInAnyOrder("TYPE_A_c1", "TYPE_B_c1", "TYPE_C_c1");
	}
}
 
Example #20
Source Project: data-highway   Author: HotelsDotCom   File: OffsetManager.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public OffsetManager(@Value("${kafka.bootstrapServers}") String brokerList) {
  Map<String, Object> props = new HashMap<>();
  props.put("bootstrap.servers", brokerList);
  props.put("group.id", GROUP_ID);
  props.put("enable.auto.commit", "false");
  props.put("key.deserializer", ByteArrayDeserializer.class.getCanonicalName());
  props.put("value.deserializer", ByteArrayDeserializer.class.getCanonicalName());
  consumer = new KafkaConsumer<>(props);
}
 
Example #21
Source Project: spring-analysis-note   Author: Vip-Augus   File: SpringJUnitJupiterConstructorInjectionTests.java    License: MIT License 5 votes vote down vote up
SpringJUnitJupiterConstructorInjectionTests(ApplicationContext applicationContext, @Autowired Person dilbert,
		@Autowired Dog dog, @Value("${enigma}") Integer enigma, TestInfo testInfo) {

	this.applicationContext = applicationContext;
	this.dilbert = dilbert;
	this.dog = dog;
	this.enigma = enigma;
	this.testInfo = testInfo;
}
 
Example #22
Source Project: sdn-rx   Author: neo4j   File: ReactiveStringlyTypeDynamicRelationshipsIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test // GH-216
void shouldWriteDynamicCollectionRelationships(@Autowired PersonWithRelativesRepository repository) {

	PersonWithStringlyTypedRelatives newPerson = new PersonWithStringlyTypedRelatives("Test");
	Map<String, List<Pet>> pets = newPerson.getPets();

	List<Pet> monsters = pets.computeIfAbsent("MONSTERS", s -> new ArrayList<>());
	monsters.add(new Pet("Godzilla"));
	monsters.add(new Pet("King Kong"));

	List<Pet> fish = pets.computeIfAbsent("FISH", s -> new ArrayList<>());
	fish.add(new Pet("Nemo"));

	List<PersonWithStringlyTypedRelatives> recorded = new ArrayList<>();
	repository.save(newPerson)
		.as(StepVerifier::create)
		.recordWith(() -> recorded)
		.consumeNextWith(person -> {
			Map<String, List<Pet>> writtenPets = person.getPets();
			assertThat(writtenPets).containsOnlyKeys("MONSTERS", "FISH");
		})
		.verifyComplete();

	try (Transaction transaction = driver.session().beginTransaction()) {
		long numberOfRelations = transaction.run(""
			+ "MATCH (t:" + labelOfTestSubject + ") WHERE id(t) = $id "
			+ "RETURN size((t)-->(:Pet))"
			+ " as numberOfRelations", Values.parameters("id", recorded.get(0).getId()))
			.single().get("numberOfRelations").asLong();
		assertThat(numberOfRelations).isEqualTo(3L);
	}
}
 
Example #23
Source Project: sdn-rx   Author: neo4j   File: RepositoryIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void loadOptionalPersonWithAllConstructorWithSpelParameters(@Autowired PersonRepository repository) {

	Optional<PersonWithAllConstructor> person = repository
		.getOptionalPersonViaQuery(TEST_PERSON1_NAME.substring(0, 2), TEST_PERSON1_NAME.substring(2));
	assertThat(person).isPresent();
	assertThat(person.get().getName()).isEqualTo(TEST_PERSON1_NAME);
}
 
Example #24
Source Project: spring-graalvm-native   Author: spring-projects-experimental   File: JdbcPetRepositoryImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public JdbcPetRepositoryImpl(DataSource dataSource, OwnerRepository ownerRepository,
        VisitRepository visitRepository) {
    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

    this.insertPet = new SimpleJdbcInsert(dataSource).withTableName("pets").usingGeneratedKeyColumns("id");

    this.ownerRepository = ownerRepository;
    this.visitRepository = visitRepository;
}
 
Example #25
Source Project: sdn-rx   Author: neo4j   File: IdGeneratorsIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void idGenerationWithNewEntityShouldWork(@Autowired ThingWithGeneratedIdRepository repository) {

	ThingWithGeneratedId t = new ThingWithGeneratedId("Foobar");
	t.setName("Foobar");
	t = repository.save(t);
	assertThat(t.getTheId())
		.isNotBlank()
		.matches("thingWithGeneratedId-\\d+");

	verifyDatabase(t.getTheId(), t.getName());
}
 
Example #26
Source Project: Milkomeda   Author: yizzuide   File: CometCollectorConfig.java    License: MIT License 5 votes vote down vote up
@Autowired
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
public void configResponseBodyAdvice(RequestMappingHandlerAdapter adapter, HandlerExceptionResolver handlerExceptionResolver) {
    if (!props.isEnableTag()) {
        return;
    }
    CometCollectorResponseBodyAdvice collectorResponseBodyAdvice = cometResponseBodyAdvice();
    // 动态添加到响应处理
    SpringMvcPolyfill.addDynamicResponseBodyAdvice(adapter.getReturnValueHandlers(), handlerExceptionResolver, collectorResponseBodyAdvice);
}
 
Example #27
Source Project: sdn-rx   Author: neo4j   File: RepositoryIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void findByLessThanEqual(@Autowired PersonRepository repository) {

	List<PersonWithAllConstructor> persons = repository.findAllByPersonNumberIsLessThanEqual(2L);
	assertThat(persons)
		.containsExactlyInAnyOrder(person1, person2);
}
 
Example #28
Source Project: sdn-rx   Author: neo4j   File: RepositoryIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void findEntityWithSelfReferencesInBothDirections(@Autowired PetRepository repository) {
	long petId;
	try (Session session = createSession()) {
		petId = session.run("CREATE (luna:Pet{name:'Luna'})-[:Has]->(daphne:Pet{name:'Daphne'})"
			+ "-[:Has]->(luna2:Pet{name:'Luna'})"
			+ "RETURN id(luna) as id").single().get("id").asLong();
	}
	Pet loadedPet = repository.findById(petId).get();

	assertThat(loadedPet.getFriends().get(0).getName()).isEqualTo("Daphne");
	assertThat(loadedPet.getFriends().get(0).getFriends().get(0).getName()).isEqualTo("Luna");

}
 
Example #29
Source Project: sdn-rx   Author: neo4j   File: ReactiveRepositoryIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void findByConvertedCustomTypeWithSpELPropertyAccessQuery(@Autowired EntityWithCustomTypePropertyRepository repository) {
	try (Session session = createSession()) {
		session.run("CREATE (:CustomTypes{customType:'XYZ'})");
	}

	StepVerifier.create(repository.findByCustomTypeCustomSpELPropertyAccessQuery(ThingWithCustomTypes.CustomType.of("XYZ")))
		.expectNextCount(1)
		.verifyComplete();
}
 
Example #30
Source Project: sdn-rx   Author: neo4j   File: DynamicLabelsIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void shouldWriteDynamicLabels(@Autowired Neo4jTemplate template) {

	SimpleDynamicLabelsWithBusinessId entity = new SimpleDynamicLabelsWithBusinessId();
	entity.id = UUID.randomUUID().toString();
	entity.moreLabels = new HashSet<>();
	entity.moreLabels.add("A");
	entity.moreLabels.add("B");
	entity.moreLabels.add("C");
	template.save(entity);
	List<String> labels = getLabels(Cypher.anyNode("n").property("id").isEqualTo(parameter("id")), entity.id);
	assertThat(labels).containsExactlyInAnyOrder("SimpleDynamicLabelsWithBusinessId", "A", "B", "C");
}